using php preg_replace to change html link's h

2019-02-14 04:43发布

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?

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

3条回答
Deceive 欺骗
2楼-- · 2019-02-14 05:26

Slight modifications to Aurelio De Rosa's answer:

'/<a(.*?)href=(["\'])(.*?)\\2(.*?)>/i'
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-14 05:27

Just use the greedy operator in your regex like this:

'/<a(.*?)href="(.*?)"(.*?)>/'
查看更多
疯言疯语
4楼-- · 2019-02-14 05:37

Instead of any char . use any not (^) quote [^"]

echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
查看更多
登录 后发表回答