Rahul Kaushik Rahul Kaushik - 7 months ago 26
PHP Question

preg_replace regex for replacing anchor tag where URL is not sample.com

I have a regex for preg_replace which replace anchor tag where some URL(e.g. sample.com) exists in href. Now what i need is a regex which will replace all other anchor tags which does not contain some URL(e.g. sample.com).

Here is my regex:

$rw = "Go to hell";
$message = "<a href='http://twitter.com'>Twitter</a><br/><a href='http://google.com'>Google</a><br/><a href='http://facebook.com'>Facebook</a>";
$message = preg_replace("/<a[^>]*\bhref\s*=\s*'(?:[^']*google.com[^']*|[^][^']*facebook.com[^']*)'>(.*)<\/a>/siU", $rw, $message);


Result is:

Twitter (with link)
Go to hell
Go to hell


What i need:

Go to hell
Google (with link)
Facebook (with link)

Answer

Change your regex pattern as shown below(using lookahead negative assertion ?!):

...
$message = preg_replace("/<a[^>]*\bhref\s*=\s*'https?:\/\/(www)?(?!(google\.com|facebook\.com))[^']*'>(.*)<\/a>/siU", $rw, $message);

print_r($message);

The output will be:

Go to hell
Google (with link)
Facebook (with link)