将字符串的最后三个单词添加到开头

时间:2012-07-21 04:24:49

标签: php

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

$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 个答案:

答案 0 :(得分:3)

爆炸,重新排列,然后爆炸应该有效。请参阅示例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)) . ".";

答案 1 :(得分: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) . ".";

或类似的应该做的伎俩。

答案 2 :(得分:1)

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

答案 3 :(得分: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)))) . '.';