【发布时间】:2018-05-30 11:26:33
【问题描述】:
我想得到一个句子的最后 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 个单词。
【问题讨论】:
-
你可以把
7改成count($pieces) - $wordsNeeded -
@u_mulder 抱歉,伙计,但您似乎有些困惑。
标签: php