php – UTF-8兼容截断功能

任何人都遇到复杂的拉丁字符,如越南语?

    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 ……

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

我需要一些帮助来削减角色,但我甚至不确定幕后发生了什么.

最佳答案 您可以使用
mb_strimwidth(PHP文档):

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

或者像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;
    }
}
点赞