Negative variable width replacement required
I have looked at many questions here (and many other websites) and some have provided hints, but no one has given me a definitive answer. I know regular expressions, but I am far from being a guru. This particular question is about regex in PHP.
I need to find words in text that is not surrounded by a hyperlink of a given class. For example, I may have
This <a href="blabblah" class="no_check">elephant</a> is green and this elephant is blue while this <a href="blahblah">elephant</a> is red.
I will need to match the second and third elephants, but not the first (identified by the "no_check" test class). Note that there can be more attributes than just href and class inside hyperlinks. I figured it out
((?<!<a .*class="no_check".*>)\belephant\b)
which works fine in regex test software, but not PHP.
Any help is appreciated. If you cannot provide a regex, but can find some kind of PHP code logic that bypasses its need, I would be equally grateful.
a source to share
I ended up using a mixed solution. It turns out I had to parse the text for certain keywords and check if they were already part of the link and if not add them to the hyperlink. The solutions presented here were very interesting, but not well-chosen for what I needed.
The idea behind using an HTML parser was good and I am currently using one in another project. So the hats go to both Alan Moore and Eric Strom for proposing this solution.
a source to share
I think the simplest approach would be to match either the full element <a>
with the "no_check" attribute, or the word you are looking for. For instance:
<a [^<>]*class="no_check"[^<>]*>.*?</a>|(\belephant\b)
If it was the word you matched it would be in capture group # 1; if not, this group must be empty or empty.
Of course, by the "simplest approach" I really mean the simplest regex approach. It would be even easier to use an HTML parser.
a source to share