php - UTF-8 兼容截断函数

标签 php mysql 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;
    }
}

关于php - UTF-8 兼容截断函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288875/

相关文章:

php - 在 PHP 中执行大型操作而不会耗尽内存?

php - 在PHP MYSQL中按 session 显示数据库中的用户数据

php - 使用 file_get_contents()/PHP 在地理定位中进行字符编码

php 和 mysql 列出数据库并循环结果

oracle - 在 oracle 中,如何更改 session 以显示 UTF8?

php - Mysqlnd 事件连接数太大。这是正常的吗?

php - 如何排列 MySQL 数据库中的项目数据,就像我的示例一样

php - 无法将信息从 PHP 表单发送到多个 mysql 数据库表

android - 将 UTF-8 编码数据发布到服务器会丢失某些字符

php - 欧洲语言的 PHP 和 MySQL 编码错误