strrev() reverses a string byte by byte. It is straightforward for simple ASCII text but is not multibyte-aware for general UTF-8 text.
$text = 'plus2net';
echo strrev($text); // ten2sulp
echo strrev('plus2net'); //ten2sulp
Syntax
$input_string = "plus2net";
echo strrev($input_string); // ten2sulp
$input_string: Input string to be reversed$st="This is a test";
echo "The string = ".$st."<br>";
$st=strrev($st);
echo "The new string after applying the strrev function = ".$st."<br>";
$st="Hello world";
//echo $st[4];
$length=strlen($st);
for($i=$length-1;$i>=0;$i--){
echo $st[$i];
}
Output is here
dlrow olleH
Encoding note: strrev() reverses bytes, not UTF-8 characters. Use a Unicode-aware approach when you need to reverse user-visible characters.
Reversing a string that contains angle brackets does not preserve valid markup. Escape the reversed result at the HTML output boundary; htmlspecialchars() prevents brackets from being interpreted as tags.
$text = "Hello <World>";
// Reverse the text first; escape it when displaying in HTML.
echo htmlspecialchars(strrev($text), ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
// Visible text: >dlroW< olleH
This example reverses the order of words without reversing the letters in each word. A simple split on spaces assumes single-space ASCII text:
$sentence = "PHP is great";
$reversed_words = implode(' ', array_reverse(explode(' ', $sentence)));
echo $reversed_words;
// Outputs: great is PHP
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| huzoor | 23-04-2012 |
| Nice Collection.. I feel very happy | |