0

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.

Tim Paine
  • 17
  • 2

3 Answers3

3

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));
Jignesh Patel
  • 1,028
  • 6
  • 10
  • This works. But I am going to do bit more research if this could be made more simpler as this answer requires three diffrent function (explode, implode, and array_splice) to do the task. – Tim Paine May 30 '18 at 11:48
1

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));
?>
prit.patel
  • 330
  • 3
  • 12
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);
Tim Paine
  • 17
  • 2
17K
  • 321
  • 3
  • 4
  • Sorry buddy but if you run your code (I have added implode now), the output is **"sentence this from words five"** which is also in reverse. – Tim Paine May 30 '18 at 11:53
  • i just thought of returning n words not the pattern of returning. Sorry for that and thank you very much @TimPaine – 17K May 30 '18 at 12:29