dongmeijian1716
dongmeijian1716
2018-05-30 11:26
浏览 43
已采纳

如何从句子中获取最后n个单词? [重复]

This question already has an answer here:

I would like to get last n (for e.g. last 5) words of a sentence. How can I get it ? The following code gives the desired result but for this requires to count the remaining words in the sentence.

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

I was hoping if there is a direct way of do this like to get first n words from a sentence.

NOTE: This is not the duplicate of How to obtain the last word of a string. I want last n words, not last nth word.

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanping1632
    duanping1632 2018-05-30 11:31
    已采纳

    For last 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));
    
    点赞 评论
  • douhuilin1152
    douhuilin1152 2018-05-30 11:31

    You can do like this

    <?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));
    ?>
    
    点赞 评论
  • duanmu5039
    duanmu5039 2018-05-30 11:45

    isn't this what you are looking for?

    $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);
    
    点赞 评论

相关推荐