Use PHP to subStr to cut length in whole words

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 = '

Page title

lorem... ...ipsum home page'; 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.

This entry was posted in Code, work and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>