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 Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/ 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. Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1447638 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" Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1451094 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); ?> Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1451097 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); Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1451103 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('')); Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1451107 Share on other sites More sharing options...
levyta Posted September 25, 2013 Author Share Posted September 25, 2013 Works great! Thanks Link to comment https://forums.phpfreaks.com/topic/281746-reverse-a-string/#findComment-1451197 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.