Masykur KonHollow
Masykur KonHollow

Reputation: 21

How to Move the first two words to the two words thereafter in PHP?

I know this is kinda weird, but I need this to complete my task.

I want to move the first two words to the two words thereafter, example is in my (error) code :

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

but the result from that code is not what i want, the result is

two three zero one eight

i want the result :

two three zero one four five six seven eight

can you help me make a better code?

Upvotes: 0

Views: 81

Answers (4)

Lake
Lake

Reputation: 913

You can also use array_splice for this case

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

or one line solution,:-)

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

Upvotes: 1

Jon Taylor
Jon Taylor

Reputation: 7905

This does the trick nicely.

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

Upvotes: 0

Gerald Versluis
Gerald Versluis

Reputation: 34013

The problem is that you overwrite the result all the time. So when it steps through your for-loop the first time the string will be

two three zero one five

The second time it will be

two three zero one six

etc.

But you will only see it ending by eight because you output the string only at the end. You should store your new string in a variable and append your next number to that. It should read something like;

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

Upvotes: 0

J. Bruni
J. Bruni

Reputation: 20492

Each time the code inside your loop runs, the $result variable receives a new value.

You should only append words at the end of the sequence to it.

So, replace you for loop by this:

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

Upvotes: 1

Related Questions