Best Answer levyta, 25 September 2013 - 01:52 PM
Works great!
ThanksGo to the full post
Best Answer levyta, 25 September 2013 - 01:52 PM
Works great!
ThanksGo to the full post
Posted 01 September 2013 - 04:37 AM
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
Posted 01 September 2013 - 04:52 AM
Posted 24 September 2013 - 02:28 PM
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"
Posted 24 September 2013 - 02:52 PM
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); ?>
My Internet Home - Dumping ground for new ideas/tips/tricks and general grievances of developing.
Firefox 17 - PHP 5.4 - MySQL 5 - Win7 [64-bit]
Rule for asking for help: If you don't show that you've tried to accomplish something, you don't deserve help.
Posted 24 September 2013 - 03:29 PM
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);
Posted 24 September 2013 - 03:45 PM
Or, assuming a constant pattern for your string:
$new_string = strrev(strtok($string, ' ')) . ' ' . strtok(' '). ' ' . strrev(strtok(''));
Posted 25 September 2013 - 01:52 PM Best Answer
Works great!
Thanks
0 members, 0 guests, 0 anonymous users