我正在尝试通过添加重定向来标记字符串中的链接。数据以字符串格式从 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”来获取字符串中所有链接的位置,并将它们存储在一个名为 positions 的数组中。该数组将填充链接开始处的字符,如下所示:
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 ( 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
);
关于php - 使用 PHP 修改字符串中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309026/