把字符串的最后三个单词放到开头


Bring last three words of a string to the beginning

我想把字符串的最后三个单词放在它的开头。例如,这两个变量:

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

应该变成:

"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."

分解、重新排列,然后内爆应该可以工作。请参阅此处的示例

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

或者类似的方法就可以了。

一定要温柔地爱我<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).".";
}

这将在的两行代码中为您提供完全相同的输出

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