【发布时间】:2015-09-27 07:54:00
【问题描述】:
我正在尝试通过添加重定向来标记字符串中的链接。数据以字符串格式从 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
)
然后我遍历位置数组并使用 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全部替换
标签: php string url hyperlink tagging