0

I tried a few functions such as str_split(), chop(), and explode(). But they don't quite do what I want.

For example: $str = "it was the best of times it was the worst of times"; The result I was looking for was to segment the $str after 5 words.
So it would look like: $new_str = "it was the best of";

Thank You.

Martin
  • 22,212
  • 11
  • 70
  • 132
  • 1
    `explode()` by space and take the first 5 elements of the resulting array. Please post what you tried and where it fails – brombeer Jun 03 '21 at 15:25
  • So, you're suggesting the following? $str = "it was the best of times it was the worst of times"; $new_str = explode(" ", $str); echo "$new_str[0] "; echo "$new_str[1] "; echo "$new_str[2] "; echo "$new_str[3] "; echo "$new_str[4] "; ?> – harry_stover Jun 03 '21 at 15:38

2 Answers2

1

Use explode to turn string into an array. Then use array_splice function with an offset of 5 in order take only first five words. Finally join them together with a space.

$str = "it was the best of times it was the worst of times";
$arr = explode(' ', $str);
array_splice($arr, 5);
$new_str = join(' ', $arr);
echo $new_str;

Prints: it was the best of

XMehdi01
  • 5,538
  • 2
  • 10
  • 34
0

Here's a short and easy way to do it:

<?php
  $sentence = "I am a very nice sentence, look at me, so many words ooh!";
  $wordsToSave = 5; //how many words you want to save
  $shortSentence = array_slice(explode(" ", $sentence), 0, $wordsToSave); //make an array out of the sentence's words and save the first ones
  $sentence = implode(" ", $shortSentence); //make a string out of that array
  echo $sentence;
?>

The output, after saving only 5 words from that:

I am a very nice
Răzvan T.
  • 360
  • 4
  • 18