在PHP中从字符串中提取所有多字节字符


Extract all multibyte characters from a string in PHP

我正在尝试实现与亚洲字符一起工作的str_word_count()版本。但是,我不知道如何在给定的UTF-8字符串中分离单字节和多字节字符。我将使用什么函数来查找字符串中的多字节字符?

例如,我可能想沿着单字节和多字节字符的边界拆分字符串。

'Test中国test中国' => array('Test','中国','test','中国');

我该怎么做呢?

有许多函数可以做到这一点,特别是Multibyte String Functions,但重要的是要注意所有多字节字符都被计数为1。下面是几个例子:

$str_en = "test";
$str_ch = '中国';
echo $str_en . " " . (str_word_count($str_en)) . " word(s)" . "'n";
echo $str_ch . " " . (mb_strlen($str_ch,'utf8')) . " word(s)" . "'n"; 
echo mb_strlen($str_ch,'utf8') + str_word_count($str_en) . " word(s) total";
输出:

test 1 word(s)
中国 2 word(s)
3 word(s) total

上面的示例使用mb_strlen,而下一个示例使用preg_match在循环遍历数组时检测非ascii字符。

$var = array('Test','中国','test','中国');
foreach($var as $char) {
    if (preg_match('/['x80-'xFF]/', $char, $match)) {
        echo $char . " - " . mb_detect_encoding($char) . " - " .  str_word_count($char) . "word(s) 'n";
        /* Detect character encoding with current detect_order */
    } else {
        /* Detect character encoding with current detect_order */
        echo $char . " - " . mb_detect_encoding($char) . " - " .  str_word_count($char) . "word(s) 'n";
    }
}

print_r($匹配)。"' n";//只显示匹配的非ascii字符

输出:

Test - ASCII - 1 word(s) 
中国 - UTF-8 - 2 word(s) 
test - ASCII - 1 word(s) 
中国 - UTF-8 - 2 word(s)