【问题标题】:How to get last n words from a sentence? [duplicate]如何从句子中获取最后 n 个单词? [复制]
【发布时间】: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


【解决方案1】:

最后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));

【讨论】:

  • 这行得通。但如果这可以变得更简单,我会做更多的研究,因为这个答案需要三个不同的函数(explode、implode 和 array_splice)来完成任务。
【解决方案2】:

你可以这样做

<?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));
?>

【讨论】:

    【解决方案3】:

    这不是你要找的吗?

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

    【讨论】:

    • 对不起,哥们,但如果你运行你的代码(我现在添加了 implode),输出是 "sentence this from words Fifth" 这也是相反的。
    • 我只是想返回 n 个单词而不是返回的模式。很抱歉,非常感谢@TimPaine
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多