2

我正在努力替换每个链接中的文本。

$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';

if(preg_match_all($reg_ex, $text, $urls))
{

    foreach($urls[0] as $url)
    {

        echo $replace = str_replace($url,'http://www.sometext'.$url,  $text);
    }

}

从上面的代码中,我得到了 3 倍相同的文本,并且链接被一一更改:每次只替换一个链接 - 因为我使用 foreach,我知道。但我不知道如何一次全部更换。你的帮助会很棒!

4

2 回答 2

2

您不要在 html 上使用正则表达式。改用DOM。话虽这么说,你的错误在这里:

$replace = str_replace(...., $text);
^^^^^^^^---                  ^^^^^---

您永远不会更新 $text,因此您会在循环的每次迭代中不断地丢弃替换。你可能想要

$text = str_replace(...., $text);

相反,因此更改“传播”

于 2013-03-05T14:48:49.307 回答
1

如果您希望最终变量包含所有替换项,请将其更改为类似这样...您基本上不会将替换后的字符串传递回“主题”。我认为这是您所期望的,因为理解这个问题有点困难。

$reg_ex = "/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$text = '<br /><p>this is a content with a link we are supposed to <a href="http://www.google.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.amazon.com">click</a></p><p>another - this is a content with a link we are supposed to <a href="http://www.wow.com">click</a></p>';

if(preg_match_all($reg_ex, $text, $urls))
{
    $replace = $text;
    foreach($urls[0] as $url) {

        $replace = str_replace($url,'http://www.sometext'.$url,  $replace);
    }

    echo $replace;
}
于 2013-03-05T14:56:27.007 回答