How to echo only a certain number of words?

I want to echo only 200 words worth of text from the string I have stored in a variable. All words after 200 will not be echoed at all. How would I do that?


$words = split(" ", $text);
for ($i = 0; ($i < 200 && $i < count($words)); $i++) {
  echo $words[$i] . " ";
}

Some similar ideas on this posting too.

If you’re using mysql database, do it in your select statement:


SELECT SUBSTRING_INDEX(text_field, ' ', 200) AS first_200_words...

Otherwise


$words = explode(' ', $text);
$first_200_words = array_slice($words, 0, 200);
echo implode(' ', $first_200_words);

or


preg_match('/(\\S+\\s*){1,200}/', $text, $m);
$first_200_words = $m[0];

1 Like

That seems real smart. :wink: