它在 comment to an answer to this question 中被暗示PHP 不能反转 Unicode 字符串。
As for Unicode, it works in PHP because most apps process it as binary. Yes, PHP is 8-bit clean. Try the equivalent of this in PHP: perl -Mutf8 -e 'print scalar reverse("ほげほげ")' You will get garbage, not "げほげほ". – jrockway
不幸的是,PHP 的 unicode 支持 atm 充其量是“缺乏”是正确的。这将 hopefully change drastically with PHP6 .
PHP MultiByte functions确实提供了处理 unicode 所需的基本功能,但它不一致并且确实缺少很多功能。其中之一是反转字符串的函数。
我当然想无缘无故地覆盖这段文字,然后看看是否可行。我创建了一个函数来完成反转此 Unicode 文本这一巨大的复杂任务,因此您可以在 PHP6 之前放松一下。
测试代码:
$enc = 'UTF-8';
$text = "ほげほげ";
$defaultEnc = mb_internal_encoding();
echo "Showing results with encoding $defaultEnc.\n\n";
$revNormal = strrev($text);
$revInt = mb_strrev($text);
$revEnc = mb_strrev($text, $enc);
echo "Original text is: $text .\n";
echo "Normal strrev output: " . $revNormal . ".\n";
echo "mb_strrev without encoding output: $revInt.\n";
echo "mb_strrev with encoding $enc output: $revEnc.\n";
if (mb_internal_encoding($enc)) {
echo "\nSetting internal encoding to $enc from $defaultEnc.\n\n";
$revNormal = strrev($text);
$revInt = mb_strrev($text);
$revEnc = mb_strrev($text, $enc);
echo "Original text is: $text .\n";
echo "Normal strrev output: " . $revNormal . ".\n";
echo "mb_strrev without encoding output: $revInt.\n";
echo "mb_strrev with encoding $enc output: $revEnc.\n";
} else {
echo "\nCould not set internal encoding to $enc!\n";
}
最佳答案
这是使用正则表达式的另一种方法:
function utf8_strrev($str){
preg_match_all('/./us', $str, $ar);
return implode(array_reverse($ar[0]));
}
关于php - 如何反转 Unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/434250/