【问题标题】:How to capture href links and replace this via PHP如何捕获href链接并通过PHP替换它
【发布时间】:2012-02-10 12:13:17
【问题描述】:

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

基本上我需要执行示例中的 2 个函数(some_function_to_save_the_links_to_array 和 some_function_to_save_the_links_to_array)。

非常感谢您的帮助!

例子:

$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 hyperlink html-parsing


【解决方案1】:
<?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;
}

【讨论】:

  • 非常感谢,似乎可以工作了,下周一我会深入研究代码以使其工作。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 2014-05-19
  • 1970-01-01
相关资源
最近更新 更多