I want to replace a word in an HTML string, but I want to exclude the replacement if the word was in the attributes of the 'img' element.
Example:
$word = 'google';
$html = 'I like google and here is its logo <img src="images/google.png" alt="Image of google logo" />';
$replacement = '<a href="http://google.com">Google</a>';
$result = preg_replace('/\s'.($word).'/u', $replacement, $html);
preg_replace will also replace the "google" words inside 'src' and 'alt' attributes, I want it to just replace the word outside the 'img' element.
Use positive lookahead
(?=.*?<.*?/>)
DEMO
EXPLANATION:
More info about Regex Lookaround
You can use the discard pattern. For instance you can use a regex like this:
Working demo
The idea behind this pattern is to discard the
google
word inside<
and>
but keep the rest:You can add many "discard" pattern you want, like: