Recipe 1.5. Reversing a String by Word or Byte


1.5.1. Problem

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

1.5.2. Solution

Use strrev( ) to reverse by byte, as in 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.

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

1.5.3. Discussion

Reversing a string by words can also be done all in one line with the code in Example 1-21.

Concisely reversing a string by word

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

1.5.4. 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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net