PHP Reference ยท String Functions
PHP strrev() function
Reference for PHP strrev(): reverse the bytes of a string, why it breaks UTF-8 text, palindrome checks and a safe multibyte alternative using mb_str_split().
strrev() returns a string with its bytes in reverse order. It is a quick tool for palindrome checks, reversing identifiers and small puzzles.
The function works on bytes, not characters. For plain ASCII that is the same thing, but a UTF-8 character that uses several bytes is torn apart, producing invalid output.
<?php echo strrev("PHP"); // PHP echo strrev("abc"); // cba
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
strrev(string $string): string
| Name | Description |
|---|---|
$string |
The string to reverse. |
Return value: the reversed string.
Usage notes
- Byte-based. Multibyte characters (UTF-8 accents, emoji, CJK) come out corrupted. Reverse an array of characters from
mb_str_split()instead, as in the second example. - Even that is not perfect: combining marks and emoji sequences are made of several code points, and reversing them separately changes their meaning.
- Reverse words, not letters: use
explode(),array_reverse()andimplode(). - Arrays are reversed with
array_reverse();strrev()only accepts strings, and numbers are converted to strings when strict types are off. - Palindrome checks: normalize case and strip punctuation first, as shown above.
- Performance: it is a single linear pass over the string, fine for very large inputs.
Related
str_split(),mb_str_split(),implode(),explode()- Lessons: Strings, Multibyte strings