Return to Snippet

Revision: 20748
at November 24, 2009 09:26 by ginoplusio


Initial Code
//$h = text
//$n = keywords to find separated by space
//$w = words near keywords to keep
function truncatePreserveWords ($h,$n,$w=5,$tag='b') {
	$n = explode(" ",trim(strip_tags($n)));	//needles words
	$b = explode(" ",trim(strip_tags($h)));	//haystack words
	$c = array();						//array of words to keep/remove
	for ($j=0;$j<count($b);$j++) $c[$j]=false;
	for ($i=0;$i<count($b);$i++) 
		for ($k=0;$k<count($n);$k++) 
			if (stristr($b[$i],$n[$k])) {
				$b[$i]=preg_replace("/".$n[$k]."/i","<$tag>\\0</$tag>",$b[$i]);
				for ( $j= max( $i-$w , 0 ) ;$j<min( $i+$w, count($b)); $j++) $c[$j]=true; 
			}	
	$o = "";	// reassembly words to keep
	for ($j=0;$j<count($b);$j++) if ($c[$j]) $o.=" ".$b[$j]; else $o.=".";
	return preg_replace("/\.{3,}/i","...",$o);
}

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

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

Initial Title
Truncate text preserving keywords

Initial Tags

                                

Initial Language
PHP