Greedy regex in php
Posted on 2005-05-02
I am trying to highlight each occurance of a certain keyword in an HTML file (i.e. outside html tags). For instance, in the following html code, I want to highlight the word "keyword":
<p> bla keyword bla keyword bla</p>
<p>keyword bla keyword</p>
I'm using this regex within the eregi_replace function (the $html_code varialbe holds the contents of an html file:
the problem is the the greedyness of the regex causes that only the last occurance of "keyword" within each html tag is highlighted, i.e the above html code becomes:
<p> bla keyword bla <b style="background-color:yellow">keyword</b> bla</p>
<p>keyword bla <b style="background-color:yellow">keyword</b></p>
As you can see, other occurances of the keyword except the last one in each html tag aren't highlighted. I know this is because the ([^<]*) part of my regex is greedy, i.e it matches the longest possible string. I have tried to add an [^(keyword)], so that it avoids matching and keyword occurances, but then it only highlights the first occurance in each html tag.
How can I addapt this regex so that it matches every occurance of the keyword in each html tag?