smarty的truncate函数截取utf-8编码的字符串乱码
如题,请教各位了,谢谢。
答案或建议:
使用以下的代码替换smarty的truncate插件即可解决truncate截取utf-8编码的字符串乱码问题。
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
function smarty_utf8_substr($str,$from,$len){
# utf8 substr
# www.bsdown.com
return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
'$1',$str);
}
function smarty_modifier_truncate($string, $length = 80, $etc = '...',
$break_words = false, $middle = false)
{
if ($length == 0)
return '';
if (strlen(utf8_decode($string)) > $length) {
$length -= strlen(utf8_decode($etc));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/u', '', smarty_utf8_substr($string, 0, $length+1));
}
if(!$middle) {
return smarty_utf8_substr($string, 0, $length).$etc;
} else {
return smarty_utf8_substr($string, 0, $length/2) . $etc . smarty_utf8_substr($string, -$length/2);
}
} else {
return $string;
}
}
/* vim: set expandtab: */
?>
转载链接:http://www.baikewenda.com/h/1103/a37254.html