Highlight text except html tags

I use the following code to highlight some keywords in the 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 β€œplain” text besides text between html tags? Since when searching for users "img" the text <img> will be highlighted and the image will no longer work.

+6
php regex preg-replace
source share
3 answers

Use the DOM parser. This is not what you want to do with regex.

+5
source share

From http://forum.phpfrance.com/vos-contributions/remplacement-selectif-hors-dans-balises-html-t199.html

 function mon_rplc_callback($capture){ global $arg; return ($arg['flag'] == 1) ? $arg['fct']($arg['from'], $arg['to'], $capture[1]).$capture[2] : $capture[1].$arg['fct']($arg['from'], $arg['to'], $capture[2]); } function split_tag($from, $to, $txt, $fct, $flag = 1){ global $arg; $arg = compact('from', 'to', 'fct', 'flag'); return preg_replace_callback('#((?:(?!<[/az]).)*)([^>]*>|$)#si', "mon_rplc_callback", $txt); } 

When $ flag == 1, the replace function is applied outside of HTML. When $ flag == -1, the replace function is applied inside HTML.

As applied to your example, it will give something like this:

 echo split_tag($words, '<span class="hightlighted_text">'.$words.'</span>', $message, 'str_ireplace', 1); 

Enjoy!;)

+2
source share

Best code based on answer from @Savageman

 $str = '<a href="ba">ba</a>'; $highlightWhat = "ba"; $str = preg_replace_callback('#((?:(?!<[/az]).)*)([^>]*>|$)#si', function($m) use ($highlightWhat) { return preg_replace('~('.$highlightWhat.')~i', '<span style="background:#fff330">$1</span>', $m[1]) . $m[2]; }, $str); 
0
source share

All Articles