Problem
You want to reverse the words or the bytes in a string.
Solution
Use strrev( ) to reverse by byte, as in Example 1-19.
Example 1-19. Reversing a string by byte
[sourcecode language="php"]<?php
print strrev('This is not a palindrome.');
?>[/sourcecode]
Example 1-19 prints:
.emordnilap a ton si sihT
To reverse by words, explode the string by word boundary, reverse the words, and then rejoin, as in Example 1-20.
Example 1-20. Reversing a string by word
[sourcecode language="php"]
<?php
$s = "Once upon a time there was a turtle.";
// break the string up into words
$words = explode(' ',$s);
// reverse the array of words
$words = array_reverse($words);
// rebuild the string
$s = implode(' ',$words);
print $s;
?>[/sourcecode]
Example 1-20 prints:
turtle. a was there time a upon Once
Discussion
Reversing a string by words can also be done all in one line with the code in Example 1-21.
Example 1-21. Concisely reversing a string by word
[sourcecode language="php"]<?php
$reversed_s = implode(' ',array_reverse(explode(' ',$s)));
?>[/sourcecode]
See Also
Recipe 23.7 discusses the implications of using something other than a space character as your word boundary; documentation on strrev( ) at http://www.php.net/strrev and array_reverse( ) at http://www.php.net/array-reverse.
Sumber: Adam Trachtenberg and David Sklar, PHP Cookbook, O'Reilly.