84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
我有个字符串,格式为$str = "中华人民abc共和\x01国",如何逐个汉字遍历该字符串呢?即:能够输出“中” “华” “人” “民” “a” ...
我现在使用的方法是:for($i =0 ; $i < len ; $i++) {$sub_str = mb_substr($str, $i, 1)},但这样做效率太低。
请问应该如何提高效率?是否可以讲$str转换为数组?
闭关修行中......
function str_split_unicode($str, $l = 0) { if ($l > 0) { $ret = array(); $len = mb_strlen($str, "UTF-8"); for ($i = 0; $i < $len; $i += $l) { $ret[] = mb_substr($str, $i, $l, "UTF-8"); } return $ret; } return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY); } $s = '中华人民abc共和\x01国'; print_r(str_split_unicode($s)); Array ( [0] => 中 [1] => 华 [2] => 人 [3] => 民 [4] => a [5] => b [6] => c [7] => 共 [8] => 和 [9] => \ [10] => x [11] => 0 [12] => 1 [13] => 国 )
//UTF8算法,其它编码自行转换
$cind = 0; $arr_cont = array(); for ($i = 0; $i < strlen($tempaddtext); $i++) { if (strlen(substr($tempaddtext, $cind, 1)) > 0) { if (ord(substr($tempaddtext, $cind, 1)) < 192) { //如果为英文则取1个字节 if (substr($tempaddtext, $cind, 1) != " ") { array_push($arr_cont, substr($tempaddtext, $cind, 1)); } $cind++; } elseif(ord(substr($tempaddtext, $cind, 1)) < 224) { array_push($arr_cont, substr($tempaddtext, $cind, 2)); $cind+=2; } else { array_push($arr_cont, substr($tempaddtext, $cind, 3)); $cind+=3; } } } print_r($arr_cont);
//UTF8算法,其它编码自行转换