DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

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

  • submit to reddit
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;