CoderZone.org

Category: >> PHP Code >> Neatly trim a string to a set number of words Bookmark and Share

<< lastnext >>

Snippet Name: Neatly trim a string to a set number of words

Description: Trim a string along a word boundary that you specify, and add '...' to the end.

Also see:
» SEO string generator
» Match all #RRGGBB or #RGB values i...
» Remove empty lines from a string o...
» Find first non-numeric character i...
» Read a web page directly in to a s...
» Multi-line variables and strings i...
» Convert a String to Title Case in ...
» Create an array from words in an H...
» Count all words in a string
» Count specific characters in a str...
» Regexp: Find and highlight repeate...
» Create an array from comma separat...
» Convert Unix time string to a date...
» Convert Dollars And Cents Value to...
» Reserved Words In Javascript
» Count Uppercase Letters In A String
» Format money as millions, billions...
» Truncate text while preserving HTM...
» Convert UK Dates To mySQL Format D...
» Search array elements for a substr...
» Add a period at the end of a strin...
» Count capital letters in a string
» Search All Words Of A String In my...
» Remove Extra Spaces From A String
» Calculate the difference between t...
» Get Query String with Javascript
» RMAN: Format Directives
» USER - connection information
» USER - User Information 2

Comment: (none)

Author: CoderZone
Language: PHP
Highlight Mode: PHP
Last Modified: May 27th, 2010

// Limit a string to a specified number of words and add '...' to end
function neat_trim($str, $n, $delim='...') {	
	$len = strlen($str);
	if ($len > $n) {
		preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
		return rtrim($matches[1]) . $delim;
	}
	else {
		return $str;
	}
}
 
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 34