When a Chinese character is truncated, according to the encoding rules, it always has to pull in other characters behind it and interpret them as Chinese characters. This is the reason why garbled characters appear. The combination of values 0x81 to 0xff and 0x00 is always displayed as "empty". According to this feature, adding a chr(0) after the substr result can prevent garbled characters.
Let's look at the code first
The code is as follows:
<?php $len = 15; $str = "这个新闻或是文章的标题很长,需要只显示前面一些字,后面用...来代替"; echo strlen($str)<=$len ? $str : (substr($str,0,$len).chr(0)."..."); ?>
chr(0) related knowledge:
null means nothing, and the value of chr(0) is 0. Expressed in hexadecimal it is 0x00, expressed in binary it is 00000000
Although chr(0) will not display anything, it is a character.
ps:
If it is UTF-8, the Chinese characters in UTF-8 are 3 bytes. The intercepted length should be a multiple of 3 as much as possible to avoid the generation of garbled characters