I am working on a 'highlight search words' BBCode modification for a forum. The idea is to highlight the search terms in the posted messages. The search terms are available in a variable called $sword Currently, the part where I add the highlighting looks like this: //highlight search terms //$sword variable contains the search terms, e.g. $sword = "music-concert"; if($sword != null) { $word_array = explode('-',$sword); while (list($i, $word) = @each($word_array)) { if($word != 'and' && $word != 'or' && $word != 'not') $text = preg_replace("|($word)|Ui" , "<span style='background-color: #FFFF00; color: #000000'>$1</span>" , $text ); } } Code (markup): Now my problem: I don't want the search terms to be highlighted in a post if it appears in a: [...img]...[/img...], [...url]...[/url...] Code (markup): bracket, or the word was found in a link. (... added - otherwise code block doesn't parse correctly in this forum.) Would appreciate if someone could help with this.
Actually I found a way how it can be done in a single line! Here it is: $text = preg_replace('/((<[^>]*)|' . preg_quote(strtr($word, array('\'' => ''')), '/') . ')/ie', "'\$2' == '\$1' ? stripslashes('\$1') : '<span style=\"background-color: #FFFF00; color: #000000\">\$1</span>'", $text); Code (markup): where $text is the message text and $word is the search term found in $text to be highlighted. I tested it with all possible BBCode - and it works perfectly. It does not corrupt links or images posted as BBCode in posts (if the search term was found in the link). Just remember that the above highlight parsing (as shown in the above code block) should be done after all the other BBCode has been parsed.