0

我已经为此绞尽脑汁好几个小时了,我需要将一些 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>

希望这是有道理的。

提前致谢,

凯尔

4

2 回答 2

0

不要重新发明轮子,只需使用以下内容:

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

这真的很容易我也使用它

于 2012-04-03T19:42:26.460 回答
0

我对 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);
于 2012-08-15T15:40:17.850 回答