Joe
Joe

Reputation: 1772

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

Upvotes: 9

Views: 35538

Answers (3)

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

Just use the greedy operator in your regex like this:

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

Upvotes: 6

Yash
Yash

Reputation: 919

Slight modifications to Aurelio De Rosa's answer:

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

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

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

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

Upvotes: 16

Related Questions