static function truncate string length 80 etc break_words false if len

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
static function truncate($string, $length = 80, $etc = '...', $break_words = false)
{
if ($length <= 0) {
return '';
}
$encoding = mb_detect_encoding($string);
if (mb_strlen($string, $encoding) > $length) {
$length -= mb_strlen($etc, $encoding);
$string = html_entity_decode($string, ENT_COMPAT, $encoding);
if (!$break_words) {
$string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length+1, $encoding));
}
$string = mb_substr($string, 0, $length, $encoding) . $etc;
}
return $string;
}