我试图通过添加重定向来标记字符串中的链接。数据以字符串格式从MySQL数据库中输出,看起来像这样:
$string = "<p><a href='http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://facebook.com'>Friend on Facebook</a></p>";
我使用函数strpos与针"http"一起获得字符串中所有链接的位置,并将它们存储在一个名为位置的数组中。数组被链接开始处的字符填充,看起来像这样:
Array
(
[0] => 12
[1] => 100
)
然后循环遍历position数组,并使用substr_replace在http之前添加重定向链接。然而,这只适用于一个链接,如果我在字符串中有多个链接,它会被覆盖。有人有什么聪明的解决办法吗?
下面是我的代码:function stringInsert($str,$pos,$insertstr)
{
if (!is_array($pos))
$pos=array($pos);
$offset=-1;
foreach($pos as $p)
{
$offset++;
$str = substr($str, 0, $p+$offset) . $insertstr . substr($str, $p+$offset);
}
return $str;
}
$string = "<p><a href='http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://facebook.com'>Friend on Facebook</a></p>";
$needle = "http";
$lastPos = 0;
$positions = array();
while (($lastPos = strpos($string, $needle, $lastPos))!== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
$str_to_insert = "http://redirect.com?link=";
foreach ($positions as $value) {
$finalstring = substr_replace($string, $str_to_insert, $value, 0);
}
最终结果应该是这样的:
$string = "<p><a href='http://redirect.com?link=http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://redirect.com?link=http://facebook.com'>Friend on Facebook</a></p>";
我认为一个更舒适的解决方案可能是使用str_replace (http://php.net/manual/en/function.str-replace.php)
执行如下操作:
$string = str_replace(
['http://','https://'],
['http://redirect.com?link=http://', 'http://redirect.com?link=https://'],
$sourceString
);
我会选择regexp:
$str = "<p><a href='http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://facebook.com'>Friend on Facebook</a></p>";
$str = preg_replace('/(['''"])(http[^'''"]+)(['''"])/', '$1http://redirect.com?link=$2$3', $str);
echo htmlspecialchars($str);
我得到的输出:<p><a href='http://redirect.com?link=http://twitter.com'>Follow on Twitter</a> and please friend on <a href='http://redirect.com?link=http://facebook.com'>Friend on Facebook</a></p>
请记住,最后一行仅用于显示目的。使用转义的html,以便您可以看到结果。对于实际工作的链接,你不需要htmlspecialchars
调用
try this
str_replace("href='", "href='http://redirect.com?link=", $string);
相反,让我们使用DOMDocument解析器,它允许我们对HTML字符串利用规范化方法。
$doc = new DOMDocument();
$doc->loadHTML($string);
现在我们可以遍历所有锚元素并进行必要的修改:
foreach( $doc->getElementsByTagName("a") as $anchor) {
$newLink = "http://example.com";
$anchor->setAttribute('href', $newLink );
}
然后你可以执行echo $doc->saveHTML();
当你完成。
您也可以在实际的foreach循环中执行条件比较。
Jquery的实现方式: