I'm using the code below to highlight some keywords in a text:
$message = str_ireplace($words,'<span class="hightlighted_text">'.$words.'</span>',$message);
The text may contain some html tags, for example <img>
, <strong>
, etc..
How can I highlight "normal" text, except the text between the html tags? Because when users search for "img" the <img>
text will be highlighted and the image doesn't work anymore.
Use a DOM parser of some sort. This is not something you want to do with regex.
From http://forum.phpfrance.com/vos-contributions/remplacement-selectif-hors-dans-balises-html-t199.html
When $flag == 1, the replacement function is applied outside HTML. When $flag == -1, the replacement function is applied inside HTML.
Applied to your example, it would give something like this:
Enjoy! ;)
Better code based on reply from @Savageman