using php preg_replace to change html link's href attribute using php preg_replace to change html link's href attribute php php

using php preg_replace to change html link's href attribute


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="(.*?)"(.*?)>/'


Slight modifications to Aurelio De Rosa's answer:

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