PHP code
<?php $len = 19; $text = "怎么将新闻的很长的标题只显示前面一些字,后面用.....来代替?"; echo strlen($text)<=$len ? $text : (substr($text,0,$len).chr(0)."...."); ?>
chr(0) is not null
null is 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.
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
Note:
Encoding No. One byte and second byte
gb2312 0xa1-0xf7 0xa1-0xfe
gbk 0x81-0xfe 0x81-0xfe 0x40-0x7e
big5 0xa1-0xf7 0x81-0xfe 0x40-0x7e
Another method:
PHP code
function csubstr($text, $limit) { $s = '; for($i=0;$i< $limit-3;$i++) { $s .= ord($text[$i])>127 ? $text[$i].$text[++$i] : $text[$i]; } return $s; }
The above only applies to gb2312 encoding. If it is UTF-8, you need to change line 4 to
PHP code
$s .= ord($text[$i])>127 ? $text[$i].$text[++$i].$text[++$i] : $text[$i];
Chinese characters in UTF-8 are 3 bytes.