php - 如何反转 Unicode 字符串

标签 php string unicode reverse

它在 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/

相关文章:

php - 如果有数百万用户,如何在用户提交后立即使用 php 从 mysql 获取详细信息

php - 启用基于客户位置的付款方式

php - 如果 UserAgent 是 iPhone,则动态更改 url 或 WordPress 主题

python - Perl 的 ucfirst() 或 s///e 在 Python 中的等价物是什么?

php - 使用PHP编程Asterisk PBX?

java - 将 EditText 获取为 String,然后显示在 Toast 中

python - 来自原始字符串的 Pandas DataFrame

java - 使用正则表达式搜索 unicode 文本

ruby-on-rails - 在 S3 中复制/重命名非拉丁命名文件时出现 AWS::S3::SignatureDoesNotMatch 异常

java - 解耦 JSON 服务中 unicode 转义导致的安全漏洞?