4

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 some help to make it cut at the character, but I'm not even sure what is going on behind the scenes here.

1
  • 1
    Does mb_internal_encoding() return the character set that you are using? Commented Jun 9, 2011 at 6:28

2 Answers 2

3

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

echo mb_strimwidth("Hello World", 0, 10, "...",'UTF-8'); works, however. I can't seem to get the default character set to be UTF-8, no matter what I do! Thanks though :)
@RVWard can't win them all! At least it works for you if you specify the character set :)
-1

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

Vietnamese Unicode FAQs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.