如何通过PHP捕获href链接并替换它


How to capture href links and replace this via PHP

我有一个php变量,其中包含一些html内容和一些href链接。我需要捕获这些链接,保存到数据库中,并将其替换为我刚刚保存的行的id(即在时事通讯应用程序中跟踪有多少人关注该链接)。

基本上,我需要做示例中的2个函数(some_function_to_save_the_links_to_array和some_functions_to_save_the_links_to_arrays)。

非常感谢你的帮助!

示例:

$var = "<html><body><h1>This is the newsletter</h1><p>Here I have <a href='http://www.google.com'>Some links</a> in the body of this <a href='http://www.yahoo.com'>Newsletter</a> and I want to extract their.</body></html>";
//Here I just no know how to do this, but I need to save http://www.google.com and http://www.yahoo.com to, maybe, an array, and save this array in a mysql db.
some_function_to_save_the_links_to_array;
while (THERE ARE VALUES IN THE ARRAY OF THE LINKS){
 save $array['X'] to db //(I already know how to do it, this is not the problem)
 $id = last inserted row in db //I know how to do it also
 function_to_replace_the_links_for_the_id;
}
echo $var;
And this is the echo:
<html><body><h1>This is the newsletter</h1><p>Here I have <a href='http://www.mysite.com/link.php?id=1'>Some links</a> in the body of this <a href='http://www.mysite.com/link.php?id=1'>Newsletter</a> and I want to extract their.

<?php
function captureLink($content) 
{
    $links = array();
    $pattern = "/<a's+href=['"'']([^>]+?)['"'']/iU";
    if(preg_match_all($pattern,$content,$matches)) {
        for($i = 0;$link = $matches[$i][1];$i++)
            array_push($links,$link);
    }
    return $links;
}
function insertLinksToDb(array $links)
{
    $linksDb = array();
    foreach($links as $link) {
        $hash_link = md5($link);
        $sql = "SELECT (id) FROM links WHERE hash LIKE :hash";
        $sth = $dbh->prepare($sql);
        $sth->bindValue(':hash',$hash_link,PDO::PARAM_STR);
        $sth->execute();
        $result = $sth->fetch(PDO::FETCH_ASSOC);
        if(!empty($result)) {
            $id = $result['id'];
            $linksDb[$id] = $link;
        } else {
            $sql = " INSERT INTO links (hash,link) VALUES(:hash,:link);";
            $sth = $dbh->prepare($sql);
            $sth->execute(array(':hash'=>$hash_link,':link',$link));
            $linksDb[PDO::lastInsertId] = $link;
        }
    }
    return $linksDb;
}
function normallizeLinks($content,array $links)
{
    foreach($links as $id => $link) {
        //str_replace working faster than strtr
        $content = str_replace($link,'/links.php?id='.$id,$content);
    }
    return $content;
}