How to reverse a string in PHP

Created
Modified

Using strrev Function

The strrev() reverse a string.

// !olleH
echo strrev("Hello!");

// does not support utf-8 encoding
strrev("Hello,世界");
!olleH

Using For Loop

FOR LOOP will start with the value of the length of the “original string – 1” value.

function Reverse($str) {
  for ($i=strlen($str) - 1, $j = 0; $j < $i ; $i--, $j++) { 
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
  }
  return $str;
}

// !olleH
echo Reverse("Hello!");
!olleH

Using the Recursion Technique and the substr

We can also reverse a string using recursion and substr() function.

function Reverse($str) {
  $len = strlen($str);

  if($len == 1) {
    return $str;
  } else {
    $len--;
    return Reverse(substr($str, 1, $len))
      .substr($str, 0, 1);
  }
}

// !olleH
echo Reverse("Hello!");
!olleH

Reverse a Unicode string

This function support utf-8 encoding, Human Language and Character Encoding Support:

function mb_strrev($str){
  $r = '';
  for ($i = mb_strlen($str); $i>=0; $i--) {
    $r .= mb_substr($str, $i, 1);
  }
  return $r;
}

// 界世,olleH
echo mb_strrev("Hello,世界");

Here's another way.

function mb_strrev($text)
{
  return join('', array_reverse(
    preg_split('~~u', $text, -1, PREG_SPLIT_NO_EMPTY)
  ));
}

// 界世,olleH
echo mb_strrev("Hello,世界");

Here's another approach using regex.

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

// 界世,olleH
echo mb_strrev("Hello,世界");

Related Tags