Skip to content

Instantly share code, notes, and snippets.

@tddewey
Created March 25, 2014 21:23
Show Gist options
  • Save tddewey/9771710 to your computer and use it in GitHub Desktop.
Save tddewey/9771710 to your computer and use it in GitHub Desktop.
Smarter Truncate
/*
* Truncate text to a number of characters somewhat intellegently...
*
* Truncates text to a number of characters, but preserves the word. Strips ending punctuation. Will always err on the side of returning more than less.
* Props to alishahnovin at hotmail dot com who posted this at php.net
*
* @param str $text Text to truncate
* @param int $numb Number of characters to truncate to
* @param str $etc Ending. Default is an ellipsis
* @return str Returns the truncated text
*/
function tdd_rp_truncate_intelligently($text,$numb,$etc = "…") {
$text = html_entity_decode($text, ENT_QUOTES, "UTF-8" );
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));
$punctuation = ".!?:;,-"; //punctuation you want removed
$text = (strspn(strrev($text), $punctuation)!=0) ? substr($text, 0, -strspn(strrev($text), $punctuation)) : $text;
$text = htmlentities($text, ENT_QUOTES, "UTF-8" );
$text = $text.$etc;
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment