我有个字符串,格式为$str = “中华人民abc共和\x01国”,如何逐个汉字遍历该字符串呢?即:能够输出“中” “华” “人” “民” “a” …
我现在使用的方法是:for($i =0 ; $i < len ; $i++) {$sub_str = mb_substr($str, $i, 1)},但这样做效率太低。
请问应该如何提高效率?是否可以讲$str转换为数组?
回复内容:
我有个字符串,格式为$str = “中华人民abc共和\x01国”,如何逐个汉字遍历该字符串呢?即:能够输出“中” “华” “人” “民” “a” …
我现在使用的方法是:for($i =0 ; $i < len ; $i++) {$sub_str = mb_substr($str, $i, 1)},但这样做效率太低。
请问应该如何提高效率?是否可以讲$str转换为数组?
+本文来源gao!%daima.com搞$代*!码9网(
搞gaodaima代码
<code class="lang-php">function str_split_unicode($str, $l = 0) {if ($l > 0) {$ret = array();$len = mb_strlen($str, "UTF-8");for ($i = 0; $i 中 [1] => 华 [2] => 人 [3] => 民 [4] => a [5] => b [6] => c [7] => 共 [8] => 和 [9] => \ [10] => x [11] => 0 [12] => 1 [13] => 国)</code>
//UTF8算法,其它编码自行转换
<code class="lang-php"><br> $cind = 0; $arr_cont = array(); for ($i = 0; $i 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);</code>