Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It was hinted in a comment to an answer to this question that PHP can not reverse Unicode strings.

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

And unfortunately it is correct that PHPs unicode support atm is at best "lacking". This will hopefully change drastically with PHP6.

PHPs MultiByte functions does provide the basic functionality you need to deal with unicode, but it is inconsistent and does lack a lot of functions. One of these is a function to reverse a string.

I of course wanted to reverse this text for no other reason then to figure out if it was possible. And I made a function to accomplish this enormous complex task of reversing this Unicode text, so you can relax a bit longer until PHP6.

Test code:

$enc = 'UTF-8';
$text = "ほげほげ";
$defaultEnc = mb_internal_encoding();

echo "Showing results with encoding $defaultEnc.

";

$revNormal = strrev($text);
$revInt = mb_strrev($text);
$revEnc = mb_strrev($text, $enc);

echo "Original text is: $text .
";
echo "Normal strrev output: " . $revNormal . ".
";
echo "mb_strrev without encoding output: $revInt.
";
echo "mb_strrev with encoding $enc output: $revEnc.
";

if (mb_internal_encoding($enc)) {
    echo "
Setting internal encoding to $enc from $defaultEnc.

";

    $revNormal = strrev($text);
    $revInt = mb_strrev($text);
    $revEnc = mb_strrev($text, $enc);

    echo "Original text is: $text .
";
    echo "Normal strrev output: " . $revNormal . ".
";
    echo "mb_strrev without encoding output: $revInt.
";
    echo "mb_strrev with encoding $enc output: $revEnc.
";

} else {
    echo "
Could not set internal encoding to $enc!
";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

here's another approach using regex:

function utf8_strrev($str){
 preg_match_all('/./us', $str, $ar);
 return implode(array_reverse($ar[0]));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...