[英]php replace links
I have been racking my brains over this for hours, I need to pass some html to a function and have it replace the links and the return the html with the replaced 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;
}
}
}
?>
When I echo the links it shows all the matched links. 当我回显链接时,它会显示所有匹配的链接。 Question is how do i return the complete HTML with the replaced links example below.
问题是如何返回下面带有替换链接示例的完整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>
Should become: 应该变成:
<!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>
Hope this makes sense. 希望这是有道理的。
Thanks in advance, 提前致谢,
Kyle 凯尔
Don't reinvent the wheel just use something like this: 不要重新发明轮子,只需使用如下所示的内容:
http://code.google.com/p/jquery-linkify/ http://code.google.com/p/jquery-linkify/
It's really easy i use it as well 我也很容易使用它
I don't know much about preg_replace, but i needed exatcly the same function as you. 我对preg_replace不太了解,但是我需要与您完全相同的功能。 Changing the line:
换行:
preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
for this: 为了这:
str_replace($match[0],$url,$text);
seems to do the trick. 似乎可以解决问题。
I just needed to get the return from this functions, so: 我只需要从此函数中获得收益,所以:
//$text = preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]);
$text = str_replace($match[0],$url,$text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.