php - 使用 PHP 修改字符串中的链接

标签 php string url hyperlink tagging

我正在尝试通过添加重定向来标记字符串中的链接。数据以字符串格式从 MySQL 数据库中出来,看起来像这样:

$string = "<p><a href='http://twitter.com'>Follow on Twitter</a>&nbsp;&nbsp;and please friend on&nbsp;<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>&nbsp;&nbsp;and please friend on&nbsp;<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>&nbsp;&nbsp;and please friend on&nbsp;<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/

相关文章:

javascript - 需要隐藏url中的变量值

url - 获取 Orchard ContentItem 显示 URL

javascript - 如何从无限循环的 Javascript 函数向 MySQL 传递值?

php - 一般错误 : 1364 Field 'location' doesn't have a default value

php - 限制一次在 PHP 中下载 1 个

php - 是什么导致错误 'Not Found SoftDeletingTrait Class' ?

c - 从 C 中的结构构建字符串

c - 将一个字符附加到一个字符 *

python - 如何遍历每个 [ :2] overlapping characters in a string of DNA code?

regex - 使用 Coldfusion 将 URL 包装在带有 href 标签的字符串中