PHP Regular expression to match keyword outside HTML tag

$str = preg_replace('~Moses(?!(?>[^<]*(?:<(?!/?a\b)[^<]*)*)</a>)~i',
                    '<a href="https://stackoverflow.com/questions/7798829/novo-mega-link.php">$0</a>', $str);

The expression inside the negative lookahead matches up to the next closing </a> tag, but only if it doesn’t see an opening <a> tag first. If that succeeds it means the word Moses is inside an anchor element, so the lookahead fails, and no match occurs.

Here’s a demo.

Leave a Comment

tech