The example of this article summarizes the PHP Chinese string interception method, very practical technique. Share to everyone for your reference. The specific methods are analyzed as follows:
Use PHP function substr intercept Chinese characters may appear garbled, mainly substr may be abruptly to a Chinese character "saw" in two.
The solution is as follows:
1, using the Mbstring expansion Library MB_SUBSTR interception will not appear garbled.
2, write the Intercept function, but the efficiency is not as high as the Mbstring expansion library.
3, if only for the output of the intercepted string, can be implemented as follows: substr ($STR, 0,). chr (0).
The substr () function can split the text, but the text to be segmented will often encounter problems if it includes Chinese characters, and this function can be/mb_strcut with Mb_substr (), Mb_substr ()/mb_strcut is similar to substr (). Only in Mb_substr ()/mb_strcut finally to add a parameter to set the string encoding, but the general server did not open the Php_mbstring.dll, need to be in the php.ini in the Php_mbstring.dll open.
Give 2 examples:
①mb_substr sample
<?php
Echo mb_substr (' So my string will not have garbled ^_^ ', 0, 7, ' utf-8 ');
Output: So my word
?>.
②mb_strcut sample
<?php
Echo mb_strcut (' So my string will not have garbled ^_^ ', 0, 7, ' utf-8 ');
Output: Such a
?>
The above example shows that MB_SUBSTR is the word to split the characters, and Mb_strcut is to split the characters by Byte, but will not produce half a character phenomenon.
PHP implementation of the text string interception without garbled method:
<?php
//This function completes strings with Chinese characters string
function Substr_cn ($str, $mylen) {
$len =strlen ($STR);
$content = ';
$count =0;
For ($i =0 $i < $len $i + +) {
if Ord (substr ($str, $i, 1)) >127 {
$content. =substr ($str, $i, 2);
$i + +;
} else{
$content. =substr ($str, $i, 1);
}
if (+ + $count = = $mylen) {break
;
}
}
echo $content;
}
$str = "34 People's Republic of China";
SUBSTR_CN ($STR, 3);//Output 34
?>
I hope this article will help you with your PHP program design.