public static function cut(string $string, int $max = 50, string $etc = '...') : string
{
// Trim whitespace
$string = trim($string);
// No trimming is needed
if (mb_strlen($string, 'utf-8') <= $max) {
return $string;
}
// Find out "etc" length
switch ($etc) {
case '…':
$etcLength = 1;
break;
default:
$etcLength = mb_strlen(html_entity_decode($etc, ENT_COMPAT, 'utf-8'), 'utf-8');
break;
}
// Look for word boundaries
$search = mb_substr($string, 0, $max - $etcLength + 1, 'utf-8');
if (preg_match('~[^\\w\\pL\\pN]~u', $search)) {
// Boundary found
$string = preg_replace('~[^\\w\\pL\\pN]*[\\w\\pL\\pN]*$~uU', '', $search);
} else {
// No word boundary found, will trim in the middle of a word
$string = mb_substr($string, 0, $max - $etcLength, 'utf-8');
}
// Add "etc" at the end
$string .= $etc;
return $string;
}