开发者

REGEX to print every word in reverse

Could anyone please help me with the regex of reversing each word in a string?

Sample input:

Hello how are you my friend?

开发者_如何学CDesired 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);

CodePad.

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
     );

CodePad.

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.");

?>

https://ideone.com/WUtzJ

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.");

?>

https://ideone.com/NT7A5


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)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜