Highlight Search Terms in Text


/ Published in: PHP
Save to your folder(s)

Highlight Search Terms in Text


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.