Fou
Fou

Reputation: 916

Bring last three words of a string to the beginning

I want to bring the last three words of a string to its beginning. For example, these two variables:

$vari1 = "It is a wonderful goodbye letter that ultimately had a happy ending.";
$vari2 = "The Science Museum in London is a free museum packed with interactive exhibits.";

Should become:

"A happy ending - It is a wonderful goodbye letter that ultimately had."
"With interactive exhibits - The Science Museum in London is a free museum packed."

Upvotes: 0

Views: 111

Answers (4)

Conner
Conner

Reputation: 31060

Exploding, rearranging, and then imploding should work. See the example here

$array = explode(" ", substr($input_string,0,-1));
array_push($array, "-");
for($i=0;$i<4;$i++)
   array_unshift($array, array_pop($array));
$output_string = ucfirst(implode(" ", $array)) . ".";

Upvotes: 3

Kris
Kris

Reputation: 6112

This will get you the exact same output that you want in only 2 lines of code

$array = explode(' ', $vari1);
echo ucfirst(str_replace('.', ' - ', join(' ', array_merge(array_reverse(array(array_pop($array), array_pop($array), array_pop($array))), $array)))) . '.';

Upvotes: 1

Matt Ramey
Matt Ramey

Reputation: 318

Make sure to love me tender. <3

function switcheroo($sentence) {
    $words = explode(" ",$sentence);
    $new_start = "";
    for ($i = 0; $i < 3; $i++) {
        $new_start = array_pop($words)." ".$new_start;
    }
    return ucfirst(str_replace(".","",$new_start))." - ".implode(" ",$words).".";
}

Upvotes: 1

Lone Shepherd
Lone Shepherd

Reputation: 1005

$split = explode(" ",$vari1);
$last = array_pop($split);
$last = preg_replace("/\W$/","",$last);
$sec = array_pop($split);
$first = array_pop($split);
$new = implode(" ",array(ucfirst($first),$sec,$last)) . " - " . implode(" ",$split) . ".";

Or similar should do the trick.

Upvotes: 1

Related Questions