0

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

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

4 回答 4

3

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

$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)) . ".";
于 2012-07-21T04:42:20.997 回答
1
$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) . ".";

或类似的应该做的伎俩。

于 2012-07-21T04:41:21.570 回答
1

一定要温柔地爱我。<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).".";
}
于 2012-07-21T04:41:49.070 回答
1

这将在 2 行代码中为您提供与您想要的完全相同的输出

$array = explode(' ', $vari1);
echo ucfirst(str_replace('.', ' - ', join(' ', array_merge(array_reverse(array(array_pop($array), array_pop($array), array_pop($array))), $array)))) . '.';
于 2012-07-21T05:06:20.383 回答