PHP Cookbook: Reversing a String by Word or Byte

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

<?php
print strrev('This is not a palindrome.');
?>

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

<?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;
?>

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

<?php
$reversed_s = implode(' ',array_reverse(explode(' ',$s)));
?>

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: