tags:

views:

114

answers:

3

What is the best way to get the first 5 words of a string? How can I split the string into two in such a way that first substring has the first 5 words of the original string and the second substring constitutes the rest of the original string

+3  A: 
<?php
$words = explode(" ", $string);
$first = join(" ", array_slice($words, 0, 5));
$rest = join(" ", array_slice($words, 5));
Kenaniah
`str_split` doesn't do what you think it does.
Amber
Agreed with @Amber, `str_split` converts the first argument to an array, [it doesn't have a signature like the one indicated here](http://php.net/manual/en/function.str-split.php)
Daniel DiPaolo
Thanks. I usually get `str_split` and `explode` mixed up. Fixed the minor oversight.
Kenaniah
+6  A: 
$pieces = explode(" ", $inputstring);
$first_part = implode(" ", array_splice($pieces, 0, 5));
$other_part = implode(" ", array_splice($pieces, 5));

explode breaks the original string into an array of words, array_splice lets you get certain ranges of those words, and then implode combines the ranges back together into single strings.

Amber
Use `explode(" ", $inputstring, 6)` to save exploding when you don't need to.
salathe
+1  A: 

The following depends strongly on what you define as a word but it's a nod in another direction, away from plain explode-ing.

$phrase = "All the ancient classic fairy tales have always been scary and dark.";
echo implode(' ', array_slice(str_word_count($phrase, 2), 0, 5));

Gives

All the ancient classic fairy


Another alternative, since everyone loves regex, would be something like:

preg_match('/^(?>\S+\s*){1,5}/', $phrase, $match);
echo rtrim($match[0]);
salathe