Reputation: 916
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
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
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
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
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