Home > Backend Development > PHP Tutorial > 中文分词 - php逐个汉字遍历字符串

中文分词 - php逐个汉字遍历字符串

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:44:50
Original
2377 people have browsed it

我有个字符串,格式为$str = "中华人民abc共和\x01国",如何逐个汉字遍历该字符串呢?即:能够输出“中” “华” “人” “民” “a” ...

我现在使用的方法是:for($i =0 ; $i

请问应该如何提高效率?是否可以讲$str转换为数组?

回复内容:

我有个字符串,格式为$str = "中华人民abc共和\x01国",如何逐个汉字遍历该字符串呢?即:能够输出“中” “华” “人” “民” “a” ...

我现在使用的方法是:for($i =0 ; $i

请问应该如何提高效率?是否可以讲$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] => 国
)
Copy after login

//UTF8算法,其它编码自行转换

<br> $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);
Copy after login

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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template