The solution to intercepting garbled characters in Chinese: First, use the inconsistent binary ranges of ASCII encoding and Chinese encoding to distinguish them; then use the [substr()] function to intercept strings.
Solution to php Chinese interception of garbled characters:
The implementation principle is relatively simple, mainly using ASCII encoding The binary range of the Chinese encoding is inconsistent with that of the Chinese encoding to distinguish them, and then the substr() function is used to intercept the string.
The code I wrote is given below. Note: I only focus on utf-8 encoding. For other encodings, the reader can manually change the function to support other encodings.
=$length){ return $str; } //初始化,统计字符串的个数, $count = 0; for($i=0;$i<$length;$i++){ //达到个数跳出循环,$i即为要截取的长度 if($count == $len){ break; } $count++; //ord函数是获取字符串的ASCII编码,大于等于十六进制0x80的字符串即为中文字符串 if(ord($str{$i}) >= 0x80){ $i +=2;//中文编码的字符串的长度再加2 } } //如果要截取的个数超过了字符串的总个数,那么我们返回全部字符串,不带省略号 if($len > $count){ return $str; }else{ return substr($str,0,$i).'...'; } }
The implementation of the above code is to use the ASCII code of single-byte characters less than 0x80. As for how many bytes to skip, it depends on the specific encoding.
Related free learning recommendations:php programming(video)
The above is the detailed content of What to do if php Chinese intercepts garbled characters. For more information, please follow other related articles on the PHP Chinese website!