交换字符串中每个单词的前两个字母

时间:2016-01-08 12:30:08

标签: php

我有一个字符串:

Hello, How Are You.

我想要这个输出:

eHllo, oHw rAe oYu.

是否有任何特殊字符并不重要,我只想反转每个单词中的前两个字母。

2 个答案:

答案 0 :(得分:1)

您可以像{/ p>一样使用preg_replace_callback

$str = "Hello, How Are You.";
echo preg_replace_callback("/([a-z]+)/i",function($m){
    return implode(array_map('strrev',str_split($m[0],2)));
},$str);

输出:

eHllo, oHw rAe oYu.

Demo

答案 1 :(得分:-1)

应该是:

$input = "Hello, How Are You.";
$newstrarr = array();

foreach (str_split($input) as $index => $char){
    if($index  & 1) { //odd
        $newstrarr[$index-1] = $char; //place odd characters 1 place to the left
    } else { //even
        $newstrarr[$index+1] = $char; //place even characters 1 place to the right
    }
}
$newstr = "";

for ($x = 0; $x < (count($newstrarr) -1); $x++) {
    $newstr .= $newstrarr[$x]; // build the string from the array
}

echo $newstr;