Truncate text preserving keywords


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

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.