title: How to reverse a Unicode string
body: <p>It was hinted in a <a href="https://stackoverflow.com/questions/433525/choosing-asp-net-over-php-or-perl#433610">comment to an answer to this question</a> that PHP can not reverse Unicode strings. </p>
  
  <blockquote>
    <p>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</p>
  </blockquote>
  
  <p>And unfortunately it is correct that PHPs unicode support atm is at best "lacking". This will <a href="http://74.125.77.132/search?q=cache:X3t6LgxXRa0J:derickrethans.nl/files/php6-unicode.pdf+php6+unicode" rel="nofollow noreferrer">hopefully change drastically with PHP6</a>. </p>
  
  <p>PHPs <a href="http://no2.php.net/manual/en/ref.mbstring.php" rel="nofollow noreferrer">MultiByte functions</a> 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.</p>
  
  <p>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.</p>
  
  <p>Test code:</p>
  
  <pre><code>$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";
  }
  </code></pre>