Solve the problem of intercepting Chinese strings with PHP

巴扎黑
Release: 2016-11-11 13:37:34
Original
1312 people have browsed it

If PHP intercepts a string in English, it is easy. Just use substr directly, and generally there will be no garbled characters. Chinese is a bit troublesome.
Two solutions are given below:
(1) Directly use the Multi-Byte function Just use the mb_substr(); function of the library. The example code is as follows

"; ?>
Copy after login

This method is simple, fast, safe, beautiful, and tempting. . . Anyway, any good words can be used to describe it, but unfortunately my GoDaddy host does not support it, so I have to find another way out
(2) Customize the Chinese string interception function, basically just write a function imitating mb_substr and call it directly, as follows The code I found for me is actually very simple

=161)) //是汉语 { $start_index+=2; } else //是英文 { $start_index+=1; } } $chr_index=$start_index; //截取 for ($i=0;$i<$len;$i++) { $asc=ord($str_input{$chr_index}); if ($asc>=161) { $return_str{$i}=chr($asc); $return_str{$i+1}=chr(ord($str_input{$chr_index+1})); $len+=1; //结束条件加1 $i++; //位置偏移量加1 $chr_index+=2; continue; } else { $return_str{$i}=chr($asc); $chr_index+=1; } } return trim($return_str); }//en
Copy after login


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
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!