比较PHP中的Unicode字符

时间:2013-01-18 05:25:51

标签: php wordpress unicode utf-8

我无法比较两个我认为应该完全相同的unicode字符。我怀疑它们的编码方式不同,但不知道如何将它们更改为相同的编码。

我要比较的字符来自缅甸Unicode块。我在php 5上运行wordpress,我正在尝试制作一个自定义插件来处理缅甸Unicode。我的所有文件都是用UTF-8编码的,但我不知道wordpress是做什么的。

以下是我正在做的事情:

function myFunction( $inputText ) {
    $outputText = '';
    $inputTextArray = str_split($inputText);
    foreach($inputTextArray as $char) {
        if ($char == "က") // U+1000, a character from the Myanmar Unicode block 
            $outputText .= $char;
    }
    return $outputText;
}
add_filter( 'the_content', 'myFunction');

在处理工作的这个阶段,该功能应该只返回它出现在内容中的位置。但是,它永远不会返回任何空字符串,即使post明显存在于帖子内容中。如果我将字符更改为任何拉丁字符,则该函数将按预期工作。

所以,我的问题是,如何对这些字符进行编码($char"က"),以便$char包含此字符时,它们相等。

1 个答案:

答案 0 :(得分:2)

str_split不知道unicode。对于多字节字符,它将以单个字符分割它们。尝试将multi-byte string functionspreg_split/u开关

一起使用
$inputTextArray = preg_split("//u", $inputText, -1, PREG_SPLIT_NO_EMPTY);

http://codepad.viper-7.com/ErFwcy

使用多字节函数mb_substr_count,您也可以减少代码。像这样,

function myFunction( $inputText ) {
    return str_repeat("က", mb_substr_count($inputText, "က"));
}

或使用正则表达式

preg_match_all("/က/u", $text, $match);
$output = implode("", $match[0]);