String Limiting


This CSS solution works on container width as opposed to string length. This technique will only work on a single lines (no line breaks) as overflow hidden is needed to make it work.

.substring {
	text-overflow: ellipsis;
	white-space: nowrap;
	overflow: hidden;
}

JavaScript provides a native method that can be called on any string. The only addition used in the function is the ability to customize the trailing characters. The JavaScript solution can be handy if you need to change the length of the string after the page has rendered.

function char_limit( string, limit, trail ){

	trail = trail ? trail : '...';
	return string.substring(0, limit) + '...';

}

The more robust solution would be on the server side if you’re not bothered about making the string longer after the page has rendered. I use two techniques one that is based on the length of character in a string and another more complex function, that works on word length. Both functions strip out any HTML tags to prevent any breaking layout issues resulting from unclosed markup.

function char_limit( $string, $limit, $trail = '...' ){

	$string = trim(strip_tags($string));
	return strlen($string) <= $limit ? string : substr($string, 0, $limit).$trail;

}

function word_limit($string = '', $limit, $trail = '...'){

	$string = strip_tags($string);

	if (trim($string) == ''){
		return '';
	}

	preg_match('/^\s*+(?:\S++\s*+){1,'.$limit.'}/u', $string, $matches);

	return rtrim($matches[0]).$trail;
}

Other Resources