如何从句子中获取最后n个单词?

时间:2018-05-30 11:26:33

标签: php

我想获得一个句子的最后n个(例如最后5个)。我怎么才能得到它 ?以下代码给出了所需的结果,但为此需要计算句子中剩余的单词。

<?php
$string = "This is an example to get last five words from this sentence";
$pieces = explode(" ", $string);
echo $first_part = implode(" ", array_splice($pieces, 0,7));
echo "<hr/>";
echo $other_part = implode(" ", array_splice($pieces, 0));
?>

我希望有一种直接的方法可以做到get first n words from a sentence

注意:这不是How to obtain the last word of a string的副本。我想要最后 n个单词,而不是最后 nth 单词。

3 个答案:

答案 0 :(得分:3)

最后5

$string = "This is an example to get last five words from this sentence";
$pieces = explode(" ", $string);
echo $first_part = implode(" ", array_splice($pieces, -5));

答案 1 :(得分:1)

你可以这样做

<?php
$string = "This is an example to get last five words from this sentence";
$pieces = explode(" ", $string);
$yourValue = 5; //set for how many words you want.
$count = count($pieces) - $yourValue;//this will do its job so you don't have to count.
echo $first_part = implode(" ", array_splice($pieces, 0,$count));
echo "<hr/>";
echo $other_part = implode(" ", array_splice($pieces, 0));
?>

答案 2 :(得分:0)

这不是你想要的吗?

$nWord = 3;
$string = "This is an example to get last five words from this sentence";
$arr = explode(" ",$string);
$output = array_slice(array_reverse($arr), 0, $nWord);
$output = implode(" ", $output);
print_r($output);