Php 用另一个替换链接
我正在努力替换每个链接中的文本Php 用另一个替换链接,php,regex,Php,Regex,我正在努力替换每个链接中的文本 $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 -
$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);
}
}
$reg\u ex=“/(http | https)\:\/\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;
$text='
这是一个我们应该链接的内容另一个-这是一个我们应该链接的内容另一个-这是一个我们应该链接的内容;
if(preg_match_all($reg_ex,$text,$url))
{
foreach($url[0]作为$url)
{
echo$replace=str_replace($url,'http://www.sometext“.$url,$text);
}
}
从上面的代码中,我得到了3倍的相同文本,并且链接一个接一个地被更改:每次只替换一个链接-因为我使用foreach,我知道。
但我不知道如何一次把它们全部替换掉。
你的帮助太好了 在html上不使用正则表达式。改用。也就是说,您的bug就在这里:
$replace = str_replace(...., $text);
^^^^^^^^--- ^^^^^---
您从不更新$text,因此在循环的每次迭代中都会不断地丢弃替换项。你可能想要
$text = str_replace(...., $text);
相反,如果您希望最后一个变量包含所有替换项,那么更改“传播”会对其进行如下更改。。。 您基本上没有将替换的字符串传递回“subject”。我想这就是你所期望的,因为理解这个问题有点困难
$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;
}
$reg\u ex=“/(http | https)\:\/\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/”;
$text='
这是一个我们应该链接的内容另一个-这是一个我们应该链接的内容另一个-这是一个我们应该链接的内容;
if(preg_match_all($reg_ex,$text,$url))
{
$replace=$text;
foreach($url[0]作为$url){
$replace=str_replace($url,'http://www.sometext“.$url,$replace);
}
回声$替换;
}
Hah!确切地谢谢你。我浪费了这么多时间,就像我想要一个花哨的名字似的!:)