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);
Instead of any char .
use any not (^) quote [^"]
echo preg_replace('/<a(.*)href="([^"]*)"(.*)>/','<a$1href="javascript:alert(\'Test\');"$3>',$string_of_text);
Just use the greedy operator in your regex like this:
'/<a(.*?)href="(.*?)"(.*?)>/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With