Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using php preg_replace to change html link's href attribute

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);
like image 587
Joe Avatar asked Jan 30 '12 00:01

Joe


2 Answers

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

echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
like image 137
Joop Eggen Avatar answered Sep 20 '22 06:09

Joop Eggen


Just use the greedy operator in your regex like this:

'/<a(.*?)href="(.*?)"(.*?)>/'
like image 36
Aurelio De Rosa Avatar answered Sep 18 '22 06:09

Aurelio De Rosa