Truncate a multibyte String to n chars
Just found out PHP already has a multibyte truncate with
mb_strimwidth
— Get truncated string with specified width
It doesn't obey word boundaries though. But handy nonetheless!
Try this:
function truncate($string, $chars = 50, $terminator = ' …') {
$cutPos = $chars - mb_strlen($terminator);
$boundaryPos = mb_strrpos(mb_substr($string, 0, mb_strpos($string, ' ', $cutPos)), ' ');
return mb_substr($string, 0, $boundaryPos === false ? $cutPos : $boundaryPos) . $terminator;
}
But you need to make sure that your internal encoding is properly set.