Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save henrytran9x/79cc6b4819d02f807303 to your computer and use it in GitHub Desktop.
Save henrytran9x/79cc6b4819d02f807303 to your computer and use it in GitHub Desktop.
Truncate a string provided by the maximum limit without breaking a word.
<?php
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
function truncateStringWords($str, $maxlen) {
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr.' ...';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment