本文介绍了兼容UTF-8的截断功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人遇到复杂的拉丁字符(例如越南语)的问题吗?

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);

输出:

BàRịa-V ....

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.

推荐答案

您可以使用 mb_strimwidth (PHP文档):

You could use mb_strimwidth (PHP Documentation):

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


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;
    }
}

这篇关于兼容UTF-8的截断功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:07