Posted By

ginoplusio on 11/24/09


Tagged

smart truncate spaces


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

JoshChris


Truncate text preserving keywords


 / Published in: PHP
 

URL: http://www.barattalo.it/2009/11/24/truncate-string-preserving-some-words-in-php/

This function truncates text preserving the keyords specified, usefull for search results that should highlight found words.

  1. //$h = text
  2. //$n = keywords to find separated by space
  3. //$w = words near keywords to keep
  4. function truncatePreserveWords ($h,$n,$w=5,$tag='b') {
  5. $n = explode(" ",trim(strip_tags($n))); //needles words
  6. $b = explode(" ",trim(strip_tags($h))); //haystack words
  7. $c = array(); //array of words to keep/remove
  8. for ($j=0;$j<count($b);$j++) $c[$j]=false;
  9. for ($i=0;$i<count($b);$i++)
  10. for ($k=0;$k<count($n);$k++)
  11. if (stristr($b[$i],$n[$k])) {
  12. $b[$i]=preg_replace("/".$n[$k]."/i","<$tag>\\0</$tag>",$b[$i]);
  13. for ( $j= max( $i-$w , 0 ) ;$j<min( $i+$w, count($b)); $j++) $c[$j]=true;
  14. }
  15. $o = ""; // reassembly words to keep
  16. for ($j=0;$j<count($b);$j++) if ($c[$j]) $o.=" ".$b[$j]; else $o.=".";
  17. return preg_replace("/\.{3,}/i","...",$o);
  18. }

Report this snippet  

You need to login to post a comment.