Reverse a Multibyte String in PHP

1 minute read

PHP's strrev is not safe to use on utf-8 strings because it reverses a string one byte at a time. So if a character consists of multiple bytes it cannot be preserved as an entity in the reversed result.

There is no Multibyte String alternative to strrev either.

We did some googling, but strangely enough all solutions we encountered were either invalid or incredibly heavy memory/code wise.

For example:

What We Came Up With

Is dead simple, but I'm putting it online anyway since it's apparently not common good.

function mb_strrev ($string, $encoding = null) {
	if ($encoding === null) {
		$encoding = mb_detect_encoding($string);

	$length   = mb_strlen($string, $encoding);
	$reversed = '';
	while ($length-- > 0) {
		$reversed .= mb_substr($string, $length, 1, $encoding);

	return $reversed;


echo    strrev('Gonçalves') . "\n"; // returns sevla??noG
echo mb_strrev('Gonçalves') . "\n"; // returns sevlaçnoG

In our tests, the above function was factor 5x more efficient in regards to memory consumption than the preg_match_all solution.

Hope this helps

Leave a Comment Right Here