PHP Cookbook: Reversing a String by Word or Byte

You want to reverse the words or the bytes in a string.

Use strrev( ) to reverse by byte, as in Example 1-19.

Example 1-19. Reversing a string by byte

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

$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

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

$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 and array_reverse( ) at

Sumber: Adam Trachtenberg and David Sklar, PHP Cookbook, O’Reilly.

Wagiman Wiryosukiro

Petani Sistem Informasi, tukang las plugin & themes Wordpress. Co-Founder Saat ini aktif sebagai Developer & kontributor di OpenMandriva Linux.

You may also like...

Leave a Reply

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

%d bloggers like this: