Skip to content

Instantly share code, notes, and snippets.

@luizventurote
Last active April 8, 2016 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luizventurote/10309332 to your computer and use it in GitHub Desktop.
Save luizventurote/10309332 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.' ...';
}
?>
@Gigabiter
Copy link

I use it a little changed

class Text
{
    public static function truncate($text, $length)
    {
        if (strlen($text) > $length) {
            $text = substr($text, 0, $length);
            if (substr($text, -1, 1) != ' ') {
                $text = substr($text, 0, strrpos($text, ' ')) . ' ...';
            }
        }
        return $text;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment