Single words separated by spaces in a line

I have a text string in the following format $ str = "word1 word2 word3 word4"

So, I want to separate each word from a line. Two words are separated by a space. How can I do this. Is there a built-in function for this?

+5
source share
3 answers

The easiest way is to use explode:

$words = explode(' ', $str);

But this only accepts fixed delimiters. splita preg_splitdo accept regular expressions, so that your words can be separated by several spaces:

$words = split('\s+', $str);
// or
$words = preg_split('/\s+/', $str);

Now you can optionally remove leading and trailing spaces with trim:

$words = preg_split('/\s+/', trim($str));
+12
source
$words = explode( ' ', $str );

: http://www.php.net/explode

+5

http://php.net/explode

edit: damn, Rob was faster

+3
source

All Articles