This question already has an answer here:
- How to obtain the last word of a string 8 answers
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.