TechniqueTo 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 ?> CommentsThe 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); } ?> |