Search code examples
phpexplode

Make php explode split sentence into words


I may be misunderstanding the documentation, but when I code

explode(" ","here's a sentence",2 )

I end up with...

Array
(
    [0] => here's
    [1] => a sentence with a few words in it
)

Is there a way to make explode return...

Array
(
    [0] => here's
    [1] => a
)

I'm trying to make it take the first two words of any string it's given and put them into an array.

Thank you


Solution

  • You need array_slice.

    $result = array_slice(explode(" ","here's a sentence", 3), 0, 2);