Posted By

giak on 01/14/10


Tagged

substr array strlen strtolower strpos


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrianCoyDesign


PHP : highlight keywords in a text


 / Published in: PHP
 

URL: http://www.giacomel.fr

  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. }

Report this snippet  

You need to login to post a comment.