Parsing text with preg_replace

Discussion in 'PHP' started by Tafalezono, Mar 29, 2009.

  1. #1
    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.
     
    Tafalezono, Mar 29, 2009 IP
  2. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #2
    You need to walk tru your content char by char, so you can find out if you are in a [​IMG]
     
    EricBruggema, Mar 30, 2009 IP
  3. Tafalezono

    Tafalezono Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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.
     
    Tafalezono, Mar 30, 2009 IP