截断中文文本


Truncating Chinese text

我们的网站是中文的,主页的一部分显示了其他页面标题的列表,最大长度为"26"(如果中文字符是用英语编写的,我假设这是使用英文字符数?我们为此使用的行是:

<?php echo anchor('projects/'.$rs->url_project_title.'/'.$rs->project_id,substr(ucfirst($rs->project_title),0,26),'style="text-decoration:none;"'); ?>

但是,如果标题确实要长,代码会按应有的方式截断它,但最后两个汉字总是显示为我猜它正在使用单词的英文版本并拆分一个汉字(不知何故)。也许我想多了!?

例如。。。。

源语言:
在国内做一个尊重艺术,能够为青年导演提供平

截断版本:
在国内做一个尊重��

您能否建议进行修改以启用所需数量的字符显示而不会导致's?

而不是substr使用mbstring函数:

echo anchor(
    'projects/' . $rs->url_project_title . '/' . $rs->project_id,
    mb_substr(ucfirst($rs->project_title), 0, 26), 
    'style="text-decoration:none;"'
);

如果您没有成功,那么 PHP 可能没有检测到字符串编码,因此请向mb_substr()提供正确的编码:

// PHP uses internal encoding mb_internal_encoding()
echo mb_substr($string, 0, 26);
// you specify the encoding - in the case you know in which encoding the input comes
echo mb_substr($string, 0, 26, 'UTF-8');
// PHP tries to detect the encoding
echo mb_substr($string, 0, 26, mb_detect_encoding($string));

有关更多信息,请参阅mb_detect_encoding()

希望这有帮助。