Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luckyshot/e46404a74c667acaade0 to your computer and use it in GitHub Desktop.
Save luckyshot/e46404a74c667acaade0 to your computer and use it in GitHub Desktop.
Trim Text nicely
/**
* Trimtext
* This function will trim text without cutting it in
* the middle of the word and adding … if longer
*/
public function trimText($text, $length) {
$words = explode(" ", $text);
$text = "";
foreach ($words as $word) {
if (strlen($text." ".$word) <= $length) {
$text .= " ".$word;
}else{
$text .= "…";
break;
}
}
return trim( $text );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment