开发者

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

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

I need 开发者_如何学JAVAsome 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):

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

Or a custom function like 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;
    }
}


Be sure to perform necessary Unicode normalization to ensure each character correspond to a single codepoint.

Vietnamese Unicode FAQs

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜