php替换链接


php replace links

我已经为此绞尽脑汁了好几个小时,我需要将一些html传递给一个函数,让它替换链接,并用替换的链接返回html。

<?php
    final static public function replace_links($campaign_id, $text) {
        $regexp = "<a's[^>]*href=('"??)([^'" >]*?)''1[^>]*>(.*)<'/a>";
        if(preg_match_all("/$regexp/siU", $text, $matches, PREG_SET_ORDER)) {
            foreach($matches as $match) {
                if(substr($match[2], 0, 2) !== '##') {  //  ignore the placeholders
                    if(substr($match[2], 0, 6) !== 'mailto') {  //  ignore email addresses
                        // $match[2] = link address
                        // $match[3] = link text
                        $url = "http://xxx.com/click?campaign_id=$campaign_id&email=##email_address##&next=" . $match[2];
                        #$text .= str_replace($match[2], $url, $text);
                        #echo $links . "'n";
                        preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
                    }
                }
                return $text;
            }
        }
    }
?>

当我回显链接时,它会显示所有匹配的链接。问题是我如何返回完整的HTML和下面的替换链接示例。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<a href="mailto:sssss">xxxx</a>
<a href="http://www.abc.com/">xxxx</a>
<a href="http://www.google.com/yeah-baby-yeah">xxxx</a>
</body>
</html>

应该变成:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<a href="mailto:sssss">xxxx</a>
<a href="https://xxx.com/click?next=http://www.abc.com/">xxxx</a>
<a href="https://xxx.com/click?next=http://www.google.com/yeah-baby-yeah">xxxx</a>
</body>
</html>

希望这是有道理的。

提前感谢

Kyle

不要重新发明轮子,只需要使用这样的东西:

http://code.google.com/p/jquery-linkify/

这真的很容易,我也使用它

我对preg_replace了解不多,但我确实需要和你一样的函数。更改线路:

preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);

为此:

str_replace($match[0],$url,$text);

似乎奏效了。

我只需要从这个函数中得到回报,所以:

//$text = preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
$text = str_replace($match[0],$url,$text);