The php string and Chinese character splitting method are directly separated using the php function "str_split". garbled characters may occur because the Chinese character length is different from the English character length, however, we can create a new function to convert characters into ascii values first, and then divide the Chinese strings correctly by judging the length of different characters, and store the results into arrays, finally, use the php function "join" to insert a percent sign between characters.
Method 1: The instance code is as follows:
Function str_split_utf8 ($ str ){
$ Split = 1;
$ Array = array ();
For ($ I = 0; $ I
$ Value = ord ($ str [$ I]);
If ($ value & gt; 127 ){
If ($ value >=192 & $ value <= 223) $ split = 2;
Elseif ($ value >=224 & $ value <= 239) $ split = 3;
Elseif ($ value >=240 & $ value <= 247) $ split = 4;
} Else {
$ Split = 1;
}
$ Key = null;
For ($ j = 0; $ j <$ split; $ j ++, $ I ++ ){
$ Key. = $ str [$ I];
}
Array_push ($ array, $ key );
}
Return $ array;
}
$ String = "php fan network www.phpfensi.com ";
$ Arr1 = str_split_utf8 ($ string );
Echo join ("%", $ arr1 );
?>
Method 2: The instance code is as follows:
$ Str = "php fan network: http://www.phpfensi.com ";
Function mbstringtoarray ($ str, $ charset ){
$ Strlen = mb_strlen ($ str );
While ($ strlen ){
$ Array [] = mb_substr ($ str, 0, 1, $ charset );
$ Str = mb_substr ($ str, 1, $ strlen, $ charset );
$ Strlen = mb_strlen ($ str );
}
Return $ array;
}
$ Arr = mbstringtoarray ($ str, "gb2312 ");
?>
Note:
1. The $ charset variable is webpage encoding, for example, "gb2312" or "UTF-8 ";
2. Method 1 requires that the server must enable the mbstring. dll extension. Otherwise, the code execution is incorrect. Therefore, if you are using a VM, consider using the following method.
Method 3: The instance code is as follows:
Function str_to_arr ($ str ){
$ L = strlen ($ str );
For ($ I = 0; $ I <$ l; $ I ++ ){
$ Arr [] = ord ($ str [$ I]) & gt; 127? $ Str [$ I]. $ str [++ $ I]: $ str [$ I];
}
Return $ arr;
}
$ Arr = str_to_arr ($ str );
?>