Function For Returning First n Characters of a Paragraph

This function will return the first n (the number you request) characters careful to not break in the middle of a word. getSummary is also removing html tags, trimming whitespace to improve accuracy, and adding an ellipsis at the end. At it’s core is the php built in function word_wrap that splits a string by a specified character which allows us to grab the 1st part.

public static function getSummary($text, $characters = 100){
	// remove any html tags
	$text = strip_tags($text);

	// remove empty space
	$text = trim($text);

	// remove new lines
	$text = str_replace("\n", ' ', $text);

	// word wrap does most of the work
	// puts newlines at breaks careful not to break words
	$text = wordwrap($text, $characters);
	$text = explode("\n", $text);

	// add ... to end
	$text = $text[0] . '...';

	return $text;
}

Leave a Reply

Your email address will not be published.