Truncate string preserving some words in PHP

When you search in Google for a string, Google highlights with bold text the words you’ve searched in the results…

Novembre 24, 2009

When you search in Google for a string, Google highlights with bold text the words you’ve searched in the results list. You can use this function to do the same thing in PHP.
It splits the text to search into an array of words and then searches each word into this array. It also marks some additional words before and some words after to let the user see some words near the searched text, and re-build the output string with the searched words and the additional words to keep.

// $h = haystack string with the text
// $n = needle string with words to search 
// $w = number of additional words to keep
// $tag = tag to use to highlight the results
function truncatePreserveWords ($h,$n,$w=5,$tag='b') {
	$n = explode(" ",strip_tags($n));	//needles words
	$b = explode(" ",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);
}

// example:
$s = truncatePreserveWords("this is a long long text, we have to truncate this text and not another one. This is the example!", "long example"); 

Watch an example here (source)

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.