Over a million developers have joined DZone.

Simple Function To Trim A String To A Set Number Of Words

·

function neat_trim($str, $n, $delim='...') {	// Limit a string to a specified number of words and add '...' to end
	$len = strlen($str);
	if ($len > $n) {
		preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
		return rtrim($matches[1]) . $delim;
	}
	else {
		return $str;
	}
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}