使用php-preg_replace更改html链接';s href属性


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);

不使用任何字符.,而使用任何非(^)引号[^"]

echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(''Test'');"$3>',$string_of_text);

只需在正则表达式中使用贪婪运算符,如下所示:

'/<a(.*?)href="(.*?)"(.*?)>/'

对Aurelio De Rosa的答案进行了轻微修改:

'/<a(.*?)href=(["''])(.*?)''2(.*?)>/i'