Articles » PHP function to summerise content in whole words substr

When using content management systems or data stored in a database to populate a web page we often only require part of the data or a short summary to be displayed. Typically most systems use a function based around PHP's substr function to shorten the data. This however has disadvantages as often words are cut short and if raw HTML is in the content end tags can be missed out causing problems elsewhere on the page. Our function will strip any HTML tags and make content safe before outputting the required quantity of complete words. It is also possible to specify an ending for your summary and choose a link as well as the linkname.

the function


$content - The content you wish to summerise.
$length - The length (in words) you wish to shorten the content to.
$ending - The characters or text to be added to the end of your summary. Not required.
$link - The url for the link. Not required.
$linkname - The name for the link. Not required.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function summary($content,$length,$ending,$link,$linkname){
	// clean content - strip html tags, special chars etc..
	$words = explode(' ', htmlentities(strip_tags($content)));
	// count how many words we are left with
	$count = count($words);
	// figure out if count is higher than the specified length and set the limit
	$limit = ($count > $length)?$length:$count;
	
	for($w = 0; $w <= $limit; $w++) {
		$output .= $words[$w];
		if($w < $limit)$output .= ' ';
	}
	
	// add the ending if set else set it to "..."
	$ending = ($ending != '')?$ending:'...';
	// if the content is going to be cut short add our ending if not add a space
	$ending = ($count > $length)?$ending:' ';
	// add the linkname if set else set it to "more"
	$linkname = ($linkname != '')?$linkname:'more';
	// create the link if it is set else no link
	$link = ($link != '')?"<a>".$linkname."</a>":"";
	
	return $output.$ending.$link;
}




Captcha Image