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