UTF-8 compatible truncate function

2020-03-24 11:21发布

问题:

Anybody run into this problem for complex Latin characters, such as Vietnamese?

    function truncate($str, $length, $append = '…') {
      $strLength = mb_strlen($str);

      if ($strLength <= $length) {
         return $str;
      }

      return mb_substr($str, 0, $length) . $append;
    }

echo truncate('Bà Rịa - Vũng Tàu!', 14);

outputs:

Bà Rịa - V�…

http://codepad.viper-7.com/GOZFB0

I need some help to make it cut at the character, but I'm not even sure what is going on behind the scenes here.

回答1:

You could use mb_strimwidth (PHP Documentation):

echo mb_strimwidth("Hello World", 0, 10, "...");

Or a custom function like Multibyte String Truncate for Smarty:

mb_truncate($string, $length = 80, $etc = '...', $charset='UTF-8',
                                  $break_words = false, $middle = false)
{
    if ($length == 0)
        return '';

    if (strlen($string) > $length) {
        $length -= min($length, strlen($etc));
        if (!$break_words && !$middle) {
            $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length+1, $charset));
        }
        if(!$middle) {
            return mb_substr($string, 0, $length, $charset) . $etc;
        } else {
            return mb_substr($string, 0, $length/2, $charset) . $etc . mb_substr($string, -$length/2, $charset);
        }
    } else {
        return $string;
    }
}


回答2:

Be sure to perform necessary Unicode normalization to ensure each character correspond to a single codepoint.

Vietnamese Unicode FAQs



标签: php mysql utf-8