替换另一个链接
问题描述:
我很努力地替换每个链接中的文本。替换另一个链接
$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,我知道了。 但我不知道如何一次全部替换它们。 你的帮助会很棒!
答
你不使用html上的正则表达式。改为使用DOM。如此说来,你的错误是在这里:
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
你永远不更新$文本,让你不断地对垃圾循环的每次迭代更换。你可能想
$text = str_replace(...., $text);
代替,这样的变化“传播”
答
如果你想最终变量包含所有的替代修改它,这样的事情... 你基本上都没有通过替换字符串回到“主题”。我认为这是你所期待的,因为这个问题有点难以理解。
$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-05 14:59:31