Truncate chinese text

Our website is in Chinese, and part of the main page shows a list of other page names at the maximum length of what works as called "26" (I assume this is used to count the English character if Chinese characters were written in English ?). The line we use for this:

<?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 really long, the code truncates it the way it should, but the last two Chinese characters are always displayed as, as I assume it uses the English version of the words and separates the Chinese character (somehow). Maybe I already thought about that !?

For instance....

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

Truncated Version:
在国内做一个尊重

Can you suggest a modification that allows you to display the desired number of characters without leading to?

+6
source share
1 answer

Instead of substr use the mbstring functions:

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

If you do not succeed, it is possible that PHP did not detect the string encoding, and therefore provide the correct encoding 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() more details.

Hope this helps.

+6
source

Source: https://habr.com/ru/post/917537/


All Articles