Could anyone please help me with the regex of reversing each word in a string?
Sample input:
Hello how are you my friend?
Desired Output
olleH woh era uoy ym ?dneirf
I want to implement this in PHP.
This gives you almost what you want.
If it isn't close enough, look into Blender's solution of exploding on spaces.
preg_replace_callback('/\b(\w+)\b/', function($match) {
return strrev($match[1]);
}, $str);
You can reverse text using plain regex (and some string functions) but it is ugly...
$length = strlen($str);
echo preg_replace(
'/' . str_repeat('(.)', $length) . '/s',
'$' . join('$', range($length, 1)),
$str
);
The code sample above is for demonstration only. Please do not ever use it :)
That can't be done in pure regex, sorry.
Here's a possibly-working PHP script:
$exploded = explode(' ', $string);
$temp = array();
for ($i = 0; $i < count(exploded); $i++) {
$temp[] = strrev(exploded[i]);
}
$temp = implode(' ', $temp);
Not Regex, but this works:
<?php
function reverseWords($text) {
$words = explode(' ', $text);
$c_words = count($words);
$outtext = "";
for ($i = 0; $i < $c_words; $i++) {
if ($i !== 0) $outtext .= " ";
$length = strlen($words[$i]);
for ($p = $length-1; $p >= 0; $p--) {
$outtext .= substr($words[$i], $p, 1);
$start--;
}
}
return $outtext;
}
echo reverseWords("This is a test.");
?>
Now, I forgot about strrev()
, so that would shorten it a bit.
EDIT
Using strrev()
:
<?php
function reverseWords($text) {
$words = explode(' ', $text);
$c_words = count($words);
$outtext = "";
for ($i = 0; $i < $c_words; $i++) {
if ($i !== 0) $outtext .= " ";
$outtext .= strrev($words[$i]);
}
return $outtext;
}
echo reverseWords("This is a test.");
?>
This is extremely trivial to accomplish without a regular expression, and I see a lot of massive solutions here, so I thought I'd post a one-liner:
$rev = implode(' ', array_map('strrev', explode(' ', $string)));