How to use .chr(0) to intercept Chinese characters and prevent garbled characters in PHP

PHP中文网
Release: 2016-07-25 08:57:09
Original
1324 people have browsed it

PHP code

<?php    
$len = 19;    
$text = "怎么将新闻的很长的标题只显示前面一些字,后面用.....来代替?";    
echo strlen($text)<=$len ? $text : (substr($text,0,$len).chr(0)."....");    
?>
Copy after login

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 = &#39;;    
    for($i=0;$i< $limit-3;$i++) {    
        $s .= ord($text[$i])>127 ? $text[$i].$text[++$i] : $text[$i];    
    }    
    return $s;    
}
Copy after login

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.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!