I have a seacrch engine that searches articles on my website. I want to be able to highlight the words the user has searched for.

Sounds easy up to yet...

$content = preg_replace('/' . $search_term . '/i', "<font color=\"red\"><b>" . $search_term . "</b></font>", $content);

BUT my articles contain HTML, so, if someone, for example, searched for "color", or "href", it would corrupt all of my layout.

Is there any way around this?

Also, is there anyway, for example, if someone types in "php is good" it would highlight each indevidual word?

Thanks

Jonathan

    Try searching these forums, I know I've at least started to help someone else with this exact kind of problem before.

      Hi yelvinton, thatnks for thank link seems to do the job in finding the places to highlight, it highlights in red (like i wanted), but it displays all of the replacements with little squares like these: [] [] []

      is it something wrong with the regxp?

      Any idea why? Here is my code:

      
      function highlight($string, $replace) {
      
      if(!empty($replace)) {
      
      $regex = '#(?!<.*?)(%s)(?![^<>]*?>)#si';
      
      $replace = split(" ", $replace);
      
      foreach ($replace as $replace_single) {
      
      $string = preg_replace(sprintf($regex, preg_quote($replace_single)), "<font color=\"red\"\>\1</font>", $string);
      
      }
      
      }
      
      return $string;
      
      // end function
      
      }
      
      

      Thanks again,

      Jonno

        Using Aidan Lister's function (which I linked to):

        <?
        include('highlight.php');
        $str = 'The quick brown fox jumped over the <a href="lazy">lazy dog\'s back</a> 12345 lazy times.';
        echo str_highlight($str,'lazy', '<span style="color:red">', '</span>');
        ?>
        

        Works fine.

        The output reads:

        The quick brown fox jumped over the <a href="lazy"><span style="color:red">lazy</span> dog's back</a> 12345 <span style="color:red">lazy</span> times.

          Write a Reply...