简体   繁体   English

UTF-8 兼容截断 function

[英]UTF-8 compatible truncate function

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�… Bà Rịa - V…

http://codepad.viper-7.com/GOZFB0 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.我需要一些帮助才能切入角色,但我什至不确定这里的幕后发生了什么。

You could use mb_strimwidth (PHP Documentation):您可以使用mb_strimwidth (PHP 文档):

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

Or a custom function like Multibyte String Truncate for Smarty :或自定义 function ,例如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;
    }
}

Be sure to perform necessary Unicode normalization to ensure each character correspond to a single codepoint.请务必执行必要的 Unicode 规范化,以确保每个字符对应于单个代码点。

Vietnamese Unicode FAQs越南语 Unicode 常见问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM