Last Updated: February 25, 2016
·
1.258K
· preclowski

Truncate string after n characters preserving whole words

function truncate_str ($str, $len = 40, $delimiter = '...')
{
    return strlen($str) > $len ? substr($str, 0, strrpos($str, ' ', -(strlen($str) - $len))) . $delimiter : $str;
}