1.6 Reversing Parts of a String


You want to reverse all the words or characters in a given string.

Technique

To reverse all the words in a string, use a combination of the preg_split() function and the array_reverse() function:

 <?php function word_reverse ($str) {     return implode ("", array_reverse (preg_split ("/\ s+/", $str))); } $str = "A rose by any other name"; $str_reversed = word_reverse ($str); print $str_reversed; // Outputs: name other any by rose A ?> 

To reverse all the characters in a string, you can use PHP's strrev() function:

 <?php $str = "A rose by any other name"; $chars_reversed = strrev ($str); print $chars_reversed; // Outputs: eman rehto yna yb esor A ?> 

Comments

The word_reverse() function uses the array_reverse() function, which is available only with PHP 4. If you're still using PHP 3, you can use the following version:

 <?php function word_reverse ($str) {     $tmp_array = preg_split ("/\s+/", $str);     for ($i = count ($tmp_array) - 1; $i > 0; $i--) {         $new_str .= $tmp_array[$i] . " ";     }     return chop ($new_str); } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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