PHP string and Chinese character splitting method

高洛峰
Release: 2016-11-29 16:07:29
Original
1308 people have browsed it

If you directly use the PHP function "str_split" to split, garbled characters will appear because the length of Chinese characters and the length of English characters are different, but we can create a new function to first convert the characters into ascii values, and then judge the lengths of different characters To correctly split the Chinese string, store the result into an array, and finally use the php function "join" to insert percent signs between characters.

Method 1, the example code is as follows:

function str_split_utf8($ str){

$split=1;

$array=array();

for($i=0;$i

$value=ord($str[$i ]);

if($value>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 example code is as follows:

$str="php fan network: http://www.phpfensi.com";

function mbstringtoarray($str,$charset) {

        $strlen=mb_strlen($str);

                                                                                                                                                                                                                                         1;

? >

Note:

1. The $charset variable is the web page encoding, such as "gb2312" or "utf-8";

2. Method 1 requires that the server must enable the mbstring.dll extension, otherwise the code execution error will occur, so For friends who use virtual hosts, you can consider using the following method.

Method 3, the example code is as follows:

function str_to_arr($str){

$l=strlen($str) ;

for($i=0;$i<$l;$i++){

$arr[]=ord($str[$i])>127?$str[$i].$str[ ++$i]:$str[$i];

}

return $arr;

}

$arr=str_to_arr($str);

?>

Related labels:
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!