PHP : highlight keywords in a text


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



Copy this code and paste it in your HTML
  1. /*
  2. neo_highlight_keywords(string $text, array $keywords, string $tag_start, string $tag_end)
  3. use : echo neo_highlight_keywords($text, $keywords, '<span>', '</span>');
  4. $keywords between $tag_start and $tag_end
  5. better match with function neo_remove_accent()
  6. */
  7. function neo_highlight_keywords($text, $keywords, $tag_start, $tag_end){
  8. $original = $text;
  9. $text = strtolower($text); // can use with function neo_remove_accent($text)
  10. $tagLen = (strlen($tag_start) + strlen($tag_end));
  11.  
  12. foreach($keywords as $keyword){
  13. $keyword = strtolower($keyword); // can use with function neo_remove_accent($text)
  14. $current = $offset = $delta = 0;
  15. $len = strlen($keyword);
  16.  
  17. while(( FALSE !== ($pos = strpos($text, $keyword, $offset)))){
  18. $original = substr($original, 0, ($pos + $delta))
  19. .$tag_start.substr($original, ($pos + $delta), $len).$tag_end
  20. .substr($original, ($pos + $delta + $len));
  21.  
  22. $delta += $tagLen; // Add String Tags Lenght
  23. $offset = $pos + 1;
  24. }
  25. }
  26. return $original;
  27. }

URL: http://www.giacomel.fr

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.