Snippets v2

Languages
My Snippets

Highlight Search Terms in Text Login or Register to Bookmark this snippet

Description PHP

This function searches the text for words supplied and wraps the word in a <span class="highlight"> tag. Use CSS to apply bold and background color formatting on your page.

The Code Download
  1. <?php
  2. function HighlightTerms($text_string,$keywords) {
  3.     //this function searches for words from the keywords, and finds matches in the text,
  4.     //and highlights (bolds) them. like google does.
  5.  
  6.     // $text_sting:    the text from which you want to highlight and return...
  7.     // $keywords:      either string or array or words that should be highlighted in the text.
  8.  
  9.     if (!is_array($keywords)) {
  10.         //explode the keywords
  11.         $keywords = explode(" ",$keywords);
  12.     }
  13.     //find matches
  14.     for ($x=0;$x<count($keywords);$x++) {
  15.         if (strlen($keywords[$x]) > 1) {
  16.             preg_match_all ("'" . $keywords[$x] . "'si", $text_string, $items);
  17.             for ($y=0;$y<count($items);$y++) {
  18.                 if (isset($items[$y][0])) {
  19.                     $text_string = str_replace($items[$y][0],'<span class="highlight">' . $items[$y][0] . '</span>',$text_string);
  20.                 }
  21.             }          
  22.         }
  23.     }
  24.     return $text_string;
  25. }
  26. ?>
Credits Contact JC

Added by JC on 11th November, 2007

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment