I apologize for resurrecting this question but I stumbled upon this thread and found a small issue. For anyone wanting a character limit that will remove words that would go above your given limit, the above answers work great. In my specific case, I like to display a word if the limit falls in the middle of said word. I decided to share my solution in case anyone else is looking for this functionality and needs to include words instead of trimming them out.
function str_limit($str, $len = 100, $end = '...')
{
if(strlen($str) < $len)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if(strlen($str) <= $len)
{
return $str;
}
$out = '';
foreach(explode(' ', trim($str)) as $val)
{
$out .= $val . ' ';
if(strlen($out) >= $len)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out . $end;
}
}
}
Examples:
echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
echo str_limit('Lorem ipsum', 100, '...');
Lorem ipsum
echo str_limit('Lorem ipsum', 1, '...');
Lorem...