Find and highlight search terms with php.

So I have a function I wrote that search_preview_text( $search_word, $search_text )

  /*  Takes a search word and looks for the first occurance of the word in the search text. It then takes the position of that word in the search text and extra 20 words from the search text.    Then highlights the search word with a strong tag.  */  function search_preview_text( $search_word, $search_text )  {            $words = preg_split( "/ /", $searched_text );          $total_words = count( $words );          $i = 0;          $start = 0;          $finish = 0;          $result = "";            foreach( $words as $word )          {                  if( stripos( $word, $search_word ) !== false )                  {                          $start = $i - 10;                          $finish = $i + 10;                          if( $start < 0 )                                  $start = 0;                          if( $finish > $total_words - 1 )                                  $finish = $total_words - 1;                            for( $j = $start; $j < $finish; $j++ )                          {                                  $result .= $words[$j]." ";                          }                            // highlight search term                          $result = str_ireplace($search_word, ''.$search_word.'', $result);                              return $result;                  }                  $i++;          }            return $result;  }

Future possible improvements?
Sentence or paragraph boundary check and remove the hardcoded 20 word limit for the preview text.
Restored by Emergency Restore

Leave a Reply

Your email address will not be published. Required fields are marked *