src/Koldy/Util.php
public static function truncate(string $string, int $length = 80, string $etc = '...', bool $breakWords = false, bool $middle = false): string
    {
        if ($length == 0) {
            return '';
        }

        $encoding = Application::getEncoding();

        if (mb_strlen($string, $encoding) > $length) {
            $length -= min($length, mb_strlen($etc, $encoding));

            if (!$breakWords && !$middle) {
                $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1, $encoding));
            }

            if (!$middle) {
                return mb_substr($string, 0, $length, $encoding) . $etc;
            } else {
                return mb_substr($string, 0, (int)round($length / 2), $encoding) . $etc . mb_substr($string, (int)round(-$length / 2), null, $encoding);
            }
        } else {
            return $string;
        }
    }
public static function truncate(string $string, int $length = 80, string $etc = '...', bool $breakWords = false, bool $middle = false): string
    {
        if ($length == 0) {
            return '';
        }

        $encoding = Application::getEncoding();

        if (mb_strlen($string, $encoding) > $length) {
            $length -= min($length, mb_strlen($etc, $encoding));

            if (!$breakWords && !$middle) {
                $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1, $encoding));
            }

            if (!$middle) {
                return mb_substr($string, 0, $length, $encoding) . $etc;
            } else {
                return mb_substr($string, 0, (int)round($length / 2), $encoding) . $etc . mb_substr($string, (int)round(-$length / 2), null, $encoding);
            }
        } else {
            return $string;
        }
    }
public static function truncate ( string $ string , int $ length = 80 , string $ etc = '...' , bool $ breakWords = false , bool $ middle = false ) : string { if ( $ length == 0 ) { return '' ; } $ encoding = Application :: getEncoding ( ) ; if ( mb_strlen ( $ string , $ encoding ) > $ length ) { $ length -= min ( $ length , mb_strlen ( $ etc , $ encoding ) ) ; if ( ! $ breakWords && ! $ middle ) { $ string = preg_replace ( '/\s+?(\S+)?$/' , '' , mb_substr ( $ string , 0 , $ length + 1 , $ encoding ) ) ; } if ( ! $ middle ) { return mb_substr ( $ string , 0 , $ length , $ encoding ) . $ etc ; } else { return mb_substr ( $ string , 0 , ( int ) round ( $ length / 2 ) , $ encoding ) . $ etc . mb_substr ( $ string , ( int ) round ( - $ length / 2 ) , null , $ encoding ) ; } } else { return $ string ; } }
Truncate the long string properly

@param string $string
@param int $length default 80 [optional]
@param string $etc suffix string [optional] default '...'
@param bool $breakWords [optional] default false, true to cut the words in text
@param bool $middle [optional] default false

@return string
@throws Exception
Truncate the long string properly