How to Reverse a String in PHP Using strrev
In this article, you will learn how to reverse a string character by
character in PHP using the built-in strrev() function. This
guide covers the basic syntax of the function, provides a practical code
example, and explains how the function processes different types of
strings.
The strrev() Function Syntax
PHP provides a convenient, built-in function called
strrev() specifically designed to reverse strings. The
syntax is highly straightforward:
strrev(string $string): stringThe function takes a single string argument and returns the reversed string.
Code Example
Here is a simple example demonstrating how to use
strrev() to reverse a standard alphanumeric string:
<?php
// Define the original string
$originalString = "Hello World!";
// Reverse the string
$reversedString = strrev($originalString);
// Output the result
echo $reversedString;
// Output: !dlroW olleH
?>In this example, the string "Hello World!" is passed to
strrev(), which swaps the position of every character from
end to start, resulting in "!dlroW olleH".
Handling Multibyte (UTF-8) Strings
It is important to note that strrev() is not
multibyte-safe. Because it reverses strings byte by byte, using it on
strings containing special characters, emojis, or non-Latin alphabets
(like Cyrillic, Arabic, or Chinese) will corrupt the output.
If you need to reverse a UTF-8 string, you should use a custom
function utilizing mb_substr() or regular expressions to
ensure characters are not broken down into raw bytes.