Oct 14 2008

Pretty Truncate String Function in PHP (substr replacement)

Category: PHPvbmendes @ 15:33

In this post, I’ll show you a function to make truncate a string. I could simply use the substr function, but it’s not that good since I can break the string in the middle of a word. So I decided to write another function to do this job. It takes 4 parameters: the string you want to truncate, the length you want, the end pattern (defaults to ‘…’) and the string encoding (defaults to UTF-8). I need the encoding because substr may split in the middle of a character, if it is multi-byte, so I use the mb_substr function.

Examples

echo limit('this is just a test',10);// will print 'this is...'
echo limit('this is just a test',30);// will print 'this is just a test'
echo limit('thisIsJustABigWord',10);// will print 'thisIsJust...'

Notice that in the first case, the string will be trucated in the middle of a word(’just’), so this word was removed also. In the second case, the string is smaller then the max size I specified, so it’s returned as it is. I the third case, the string is just a big word, bigger then the max size, so the word is breaked because this is the only solution i have.

Code

function limit($string,$length,$end='...',$encoding=null){
	if(!$encoding) $encoding = 'UTF-8';
	$string = trim($string);
	$len = mb_strlen($string,$encoding);
	if($len <= $length) return $string;
	else {
		$return = mb_substr($string,0,$length,$encoding);
		return (preg_match('/^(.*[^\s])\s+[^\s]*$/', $return, $matches) ? $matches[1] : $return).$end;
	}
}

In the code, I firstly remove the spaces in the start and end of the string, then I get the lenght of my string, if it’s lower then what I want, return the string itself, otherwise, return the truncated with the end pattern.

Hope it helps.

Tags: , , , ,

One Response to “Pretty Truncate String Function in PHP (substr replacement)”

  1. nick says:

    i love the nod to us utf-8 folks.

Leave a Reply