【问题标题】:UTF-8 compatible truncate functionUTF-8 兼容的截断函数
【发布时间】:2011-06-09 06:26:00
【问题描述】:

对于复杂的拉丁字符(例如越南语),有人遇到过这个问题吗?

    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_internal_encoding() 是否返回您正在使用的字符集?

标签: php mysql utf-8


【解决方案1】:

您可以使用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;
    }
}

【讨论】:

  • echo mb_strimwidth("Hello World", 0, 10, "...",'UTF-8'); 有效。无论我做什么,我似乎都无法将默认字符集设置为 UTF-8!不过谢谢:)
  • @RVWard 无法赢得所有人!如果您指定字符集,至少它对您有用:)
【解决方案2】:

请务必执行必要的 Unicode 规范化,以确保每个字符对应于单个代码点。

Vietnamese Unicode FAQs

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2011-09-14
    • 2011-10-19
    相关资源
    最近更新 更多