如何在PHP中将前两个单词移到后面的两个单词?

时间:2012-07-06 11:45:21

标签: php

我知道这有点奇怪,但我需要这个来完成我的任务

我想将前两个单词移到后面的两个单词中,例如在我的(错误)代码中:

<?
$sentence = "zero one two three four five six seven eight";
$sentence2 = explode (" ",$sentence);
$total = count($sentence2);
for ($i = 4; $i < $total; ++$i) {
$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1]."  ".$sentence2[$i];
}
echo "Original sentence : ".$sentence;
echo "<br>Result : ".$result;
?>

但该代码的结果不是我想要的,结果是

two three zero one eight

我想要结果:

two three zero one four five six seven eight
你可以帮我制作更好的代码吗?

4 个答案:

答案 0 :(得分:1)

每次循环中的代码运行时,$result变量都会收到一个新值。

您应该只在序列末尾附加字词。

所以,用这个替换你for循环:

$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1];
for ($i = 4; $i < $total; ++$i) {
    $result .= "  ".$sentence2[$i];
}

答案 1 :(得分:1)

您也可以在此案例中使用array_splice

$sentence = "zero one two three four five six seven eight";
$words    = explode(" ",$sentence,3);
$base     = explode(" ",$words[2]);
array_splice($base,2,0,array($words[0],$words[1]));
echo implode(" ",$base);

或一线解决方案,: - )

echo preg_replace('#^(\w+\s+)(\w+\s+)(\w+\s+)(\w+\s+)#','$3$4$1$2',$sentence);

答案 2 :(得分:0)

问题是您始终覆盖结果。 所以当它第一次遍历你的for循环时,字符串将是

two three zero one five

第二次

two three zero one six

但是你只会看到它以8结尾,因为你只在最后输出字符串。 您应该将新字符串存储在变量中,并将下一个数字附加到该变量中。 它应该读起来像;

<?
$sentence = "zero one two three four five six seven eight";
$sentence2 = explode (" ",$sentence);
$total = count($sentence2);
$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1]."  ";
for ($i = 4; $i < $total; ++$i) {
$result = $result."  ".$sentence2[$i];
}
echo "Original sentence : ".$sentence;
echo "<br>Result : ".$result;
?>

答案 3 :(得分:0)

这很好地解决了这个问题。

$sentence = "zero one two three four five six seven eight";
$sentenceParts = explode (" ",$sentence);

$itemCount = count($sentenceParts);
$result = $sentenceParts[2]." ".$sentenceParts[3]." ";
for($i = 0; $i < $itemCount; $i++) {
    if($i != 2 && $i !=3) {
        $result .= $sentenceParts[$i]." ";
    }
}

echo $result;