简体   繁体   English

截断中文文本

[英]Truncating Chinese text

Our website is in Chinese and a part of the main page shows a list of other page titles at a maximum length of what works out as being called '26' (I assume this is using the English character count if the Chinese characters were written using English?). 我们的网站是中文的,主页的一部分显示了其他页面标题的列表,最大长度为“ 26”(如果汉字是使用英文写的,我假设这是英文字符计数)英语?)。 The line we use for this is: 我们用于此的行是:

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

However, if the title is indeed to long the code truncates it as it should but the final two Chinese characters are always shown as as I'm guessing it's using the English version of the words and splitting a Chinese character (somehow). 但是,如果标题确实很长,则代码会按原样将其截断,但是最后两个汉字始终显示为 ,因为我猜它使用的是英文版本的单词并拆分了汉字(以某种方式)。 Maybe I'm over thinking this!? 也许我在想这个!!

For example.... 例如....

Original: 原版的:
在国内做一个尊重艺术,能够为青年导演提供平

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

Can you perhaps suggest a modification to enable the desired number of characters show without resulting in the 's? 您是否可以建议进行修改以显示所需数量的字符而不会导致出现 ?

Instead of substr use mbstring functions: 代替substr使用mbstring函数:

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

If You are not successful with this, then it is possible that PHP didn't detect the string encoding and therefore please provide the right encoding to the mb_substr() : 如果您不成功,则可能是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));

See mb_detect_encoding() as well for further information. 另请参见mb_detect_encoding()以获取更多信息。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM