levyta Posted September 1, 2013 Share Posted September 1, 2013 I have a sting, containing numbers and letters, such that: abc 12,345 def I want reversing only the words, so the result will look: def 12,345 abc. I know how to reverse the all string: $array = explode(" ", $string);foreach ($array as &$word) { $word = strrev($word);}$rev_string = implode(" ", $array); but don't know how to deal with the numbers. Thanks Quote Link to comment Share on other sites More sharing options...
kicken Posted September 1, 2013 Share Posted September 1, 2013 Based on your example, explode() the string into individual words, array_reverse the result to reverse the order of the words, then implode it back together again. No need to loop the array or use strrev. Quote Link to comment Share on other sites More sharing options...
levyta Posted September 24, 2013 Author Share Posted September 24, 2013 Thanks for the answer. What if I want to reverse only the letters? e.g., $string = "abc 12,345 def" I want to have: $string = "cba 12,345 fed" Quote Link to comment Share on other sites More sharing options...
PaulRyan Posted September 24, 2013 Share Posted September 24, 2013 Try this <?PHP $string = "abc 12,345 def"; $stringElements = explode(' ', $string); foreach($stringElements AS $key => $element) { if(preg_match('/[a-z]/', $element)) { $stringElements[$key] = strrev($element); } } echo implode(' ', $stringElements); ?> Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted September 24, 2013 Share Posted September 24, 2013 PHP >= 5.3.0 $new_string = preg_replace_callback('/[a-zA-Z]+/', function($m) { return strrev($m[0]); }, $string); PHP < 5.3.0 $new_string = preg_replace('/([a-zA-Z]+)/e', 'strrev("$1")', $string); Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted September 24, 2013 Share Posted September 24, 2013 Or, assuming a constant pattern for your string: $new_string = strrev(strtok($string, ' ')) . ' ' . strtok(' '). ' ' . strrev(strtok('')); Quote Link to comment Share on other sites More sharing options...
Solution levyta Posted September 25, 2013 Author Solution Share Posted September 25, 2013 Works great! Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.