WP-Mix

A fresh mix of code snippets and tutorials

PHP Truncate Text at Word

Here is a PHP snippet to truncate a string of text at the specified number of words. This is a nice alternative to just shortening a string of text based on character count. With this technique, the truncated string contains only complete words and is readable.

Truncate text at word

The following function can be used to truncate the input string at the nearest word, or the nearest sentence.

// truncate string at word
function shapeSpace_truncate_string_at_word($string, $limit, $break = ".", $pad = "...") {  
	
	if (strlen($string) <= $limit) return $string;
	
	if (false !== ($max = strpos($string, $break, $limit))) {
		 
		if ($max < strlen($string) - 1) {
			
			$string = substr($string, 0, $max) . $pad;
			
		}
		
	}
	
	return $string;
	
}

This function accepts the following parameters:

  • $string – (required) string to be truncated
  • $limit – (required) number of characters
  • $break – (optional) where to break the string
  • $pad – (optional) text to append to shortened string

For the $break variable, the default value is a period, which will truncate the string at the nearest sentence. To truncate at the nearest word, use a blank space for the $break variable.

Bonus: Truncate string at nearest character

It’s not always necessary to truncate a string at a specific word. In such cases, here is a simple function to truncate a string based on the number of characters.

// truncate string at character
function shapeSpace_truncate_string_at_character($string, $max = 50, $rep = '') {
	
	$leave = $max - strlen ($rep);
	
	return substr_replace($string, $rep, $leave);
	
}

Here are the parameters accepted by this function:

  • $string – (required) string to be truncated
  • $max – (required) number of characters
  • $rep – (optional) replacement for removed part of string

The best way to see how either of the above functions work is to try them out. Drop ’em in a PHP file and experiment, always an enjoyable way to spend to a few minutes :)

Related

★ Pro Tip:

USP ProSAC Pro