Tinostarn
Tinostarn

Reputation: 101

Find a word not contained in a tag

I'm trying to make a regex that matches a word not contained in a "a" tag, I have to replace some terms with a link, without breaking links that already exist. For example, searching for the term "stackoverflow", this should match

stackoverflow is magic

But none of these two should :

Jump to <a href="stackoverflow.com">stackoverflow</a>

How can I do it ? Even if I use a HTML Parser, I still face this problem on how to apply my preg_replace on a term not contained in a "a" tag.

I've found this regex that sounded good :

(?![^<]*a>)stackoverflow

But unfortunately, this doesn't work in PHP. Thanks a lot for your help

Upvotes: 0

Views: 95

Answers (1)

bobble bubble
bobble bubble

Reputation: 26

Your regex fails if there is any a> in the line.


Skip the links like this by using (*SKIP)(*F) verbs | match word.

/<a[\s>][\s\S]*?\/a>(*SKIP)(*F)|stackoverflow/i

\s matches a whitespace, [\s\S] matches any character.

Upvotes: 1

Related Questions