froehoel
2/28/2015 - 7:07 PM

From http://www.sanwebe.com/2012/11/useful-php-functions-copy-paste

function truncate($text, $length = 0)
{
        if ($length > 0 && strlen($text) > $length) // Truncate the item text if it is too long.
        {
                $tmp = substr($text, 0, $length); // Find the first space within the allowed length.
                $tmp = substr($tmp, 0, strrpos($tmp, ' '));
                if (strlen($tmp) >= $length - 3) { // If we don't have 3 characters of room, go to the second space within the limit.
                        $tmp = substr($tmp, 0, strrpos($tmp, ' '));
                }
                $text = $tmp.'...';
        }
        return $text;
}