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.

Recommended

Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

Settembre 2, 2016

How to add rel=”nofollow” to links with preg_replace()

Adding rel="nofollow" to external link is a good SEO practice.

Settembre 22, 2015

Block junk emails, spammers and temporary emails

If you need an Email Validator Function, consider this version that includes also the check against common temporary mail services…

Dicembre 3, 2013

How many times a web link has been shared on Twitter

Twitter share button and Facebook share button are the most used buttons to share links on Internet. You can read…

Ottobre 19, 2012

get MySpace events with a PHP function

Here is a function to read the concerts for a myspace band page. This code retrieves the “shows page” for…

Febbraio 21, 2011

Php Function to resize video from YouTube and Vimeo

When you make a web application that let the user insert video embeds coming from YouTube or from Vimeo, or…

Ottobre 6, 2010