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…

November 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])) {
				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)


I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of and and I'm actually the Chief Technical Officer of Better Days web agency.


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…

September 2, 2016

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

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

September 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…

December 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…

October 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…

February 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…

October 6, 2010