有人遇到过复杂拉丁字符(例如越南语)的这个问题吗?
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/