我在努力更换每个链接中的文字。
$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,我知道。 但我不知道如何立即更换它们。 你的帮助会很棒!
答案 0 :(得分:2)
你不能在html上使用正则表达式。请改用DOM。话虽这么说,你的错误就在这里:
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
你永远不会更新$ text,所以你不断在循环的每次迭代中删除替换。你可能想要
$text = str_replace(...., $text);
相反,所以更改&#34;传播&#34;
答案 1 :(得分: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;
}