使用 php preg_replace 更改 html 链接的 href 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9058158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using php preg_replace to change html link's href attribute
提问by Joe
I'm trying to replace all link href's in a large string with a different URL. With the following code It seems to replace only the 2nd link leaving the first one intact, can someone help me out?
我正在尝试用不同的 URL 替换大字符串中的所有链接 href。使用以下代码似乎只替换了第二个链接,而第一个链接完好无损,有人可以帮我吗?
$string_of_text = '<a href="http://www.php.net/">PHP</a> <a href="http://www.apache.org/">Apache</a>';
echo preg_replace('/<a(.*)href="(.*)"(.*)>/','<ahref="javascript:alert(\'Test\');">',$string_of_text);
回答by Joop Eggen
Instead of any char .
use any not (^) quote [^"]
.
使用任何非 (^) 引号代替任何字符[^"]
echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<ahref="javascript:alert(\'Test\');">',$string_of_text);
回答by Aurelio De Rosa
Just use the greedy operator in your regex like this:
只需在您的正则表达式中使用贪婪运算符,如下所示:
'/<a(.*?)href="(.*?)"(.*?)>/'
回答by Yash
Slight modifications to Aurelio De Rosa's answer:
对 Aurelio De Rosa 的回答稍作修改:
'/<a(.*?)href=(["\'])(.*?)\2(.*?)>/i'