0

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

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

<?
$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

4 回答 4

1

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

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

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

$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1];
for ($i = 4; $i < $total; ++$i) {
    $result .= "  ".$sentence2[$i];
}
于 2012-07-06T11:49:02.283 回答
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);
于 2012-07-06T11:58:34.307 回答
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;
?>
于 2012-07-06T11:50:23.280 回答
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;
于 2012-07-06T11:55:08.490 回答