[英]using php preg_replace to change html link's href attribute
我正在尝试用不同的 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="(.*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
而不是任何char .
使用任何不(^)引用[^"]
echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
只需在正则表达式中使用贪婪的运算符,如下所示:
'/<a(.*?)href="(.*?)"(.*?)>/'
对Aurelio De Rosa的回答略有修改:
'/<a(.*?)href=(["\'])(.*?)\\2(.*?)>/i'
$content_html = preg_replace('/<a(.*?)href="(.*?)"(.*?)>/', '<a href="'. the_new_link.'">' ,$content_html);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.