我在此也把我的解决方法和大家共同分享一下,供大家参考。我也使用phpbb 3,但我发现在首页论坛列表处的最新文章处的标题字数显示不正常。如果不截断,是没有什么问题的,一旦截断标题字符,那么英文和中文字数相同的情况下,英文标题要比中文标题短很多,在中英文混杂的情况下,最新文章这儿显得长短不一,影响美观...
这个问题涉及到了PHP对多字节字符处理的问题。PHPBB3的字符截取函数定义在 includes/functions_content.php里面,函数名为truncate_string,它的功能是截取字符,对多字节字符(比如说中文字符),无论是几字节的,都以一个字符为长度。但同样长度的中、英文字符的长度是不一致的,因此会造成视觉上的长短不一。
核心数据论坛对此函数进行了改动。这里使用了一个非标准PHP库的函数mb_strimwidth,使用它之前要确保PHP加载了mbstring库。改写后的truncate_string将先以单字节来判断标题文字是否超过设置长度,如字数超出设置,就调用mb_strimwidth函数进行截取。因为处理前是以单个字符长度来检测的,中英文字符都以最小单位char来计数的,所以固定长度的char其长度是完全一致的。改后的truncate_string如下:
代码: 全选
function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = false, $append = '')
{
$strip_reply = false;
$stripped = false;
if ($allow_reply && strpos($string, 'Re: ') === 0)
{
$strip_reply = true;
$string = substr($string, 4);
}
if (strlen($string) > $max_length)
{
$string = mb_strimwidth($string,0,$max_length-utf8_strlen($append),$append,'UTF-8');
$stripped = false;
}
// Due to specialchars, we may not be able to store the string...
if (utf8_strlen($string) > $max_store_length)
{
// let's split again, we do not want half-baked strings where entities are split
$_chars = utf8_str_split(htmlspecialchars_decode($string));
$chars = array_map('utf8_htmlspecialchars', $_chars);
do
{
array_pop($chars);
$string = implode('', $chars);
}
while (!empty($chars) && utf8_strlen($string) > $max_store_length);
}
if ($strip_reply)
{
$string = 'Re: ' . $string;
}
if ($append != '' && $stripped)
{
$string = $string . $append;
}
return $string;
}
显示的标题最大字符数需要在 includes/functions_display.php中查找
代码: 全选
$last_post_subject_truncated = truncate_string($last_post_subject, 30, 255, false, $user->lang['ELLIPSIS']);