Use PHP to subStr to cut length in whole words Tags:, ,

In work, we often output a section of content and don’t always either want the whole content, or want a quick summary;

Below is a quick piece of code that will create a quick clean summary of a full HTML page from our ( or any ) content Management System.
This doesnt actually use PHP’s substr function, but has the same effect.

function summary($content, $length = 20, $finish = '…') {
	// Clean and explode our content, Strip all HTML tags, and special charactors.
	$words = explode(' ', strip_tags(preg_replace('/[^(\x20-\x7F)]*/','', $content)));
	// Get a count of all words, and check we have less/more than our required amount of words.
	$count = count($words);
	$limit = ($count > $length)?$length:$count;
	// if we have more words than we want to show, add our ...
	$end   = ($count > $length)?$finish:'';
	// create output
	for($w = 0;$w< =$limit;$w++) {
		$output .= $words[$w];
		if($w < $limit) $output .= ' ';
	}
	// return end result.
	return $output.$end;
}

Sample Usage:

// our page cntent from our SQL database... example.
$page_content = '
<h1>Page title</h1>
lorem... ...ipsum
 
<a href="#">home page</a>';
 
echo summary($page_content, 5);

This will output…

‘Page title lorem lemon…’

This will output full words rather than cutting at a certain amount of letter, and some times ending half way trough a word.

Related posts:

  1. Controlling Input with Mootools Javascript
  2. Displaying Ordered Directory Listings
  3. Clean Dynamic Directory Listing with PHP
  4. Non-Ascii charactors in my AJAX responses !?
  5. Using PHP exec to backup mySQL databases.

Subscribe Via Email Notify me of followup comments via e-mail