'PHP: Trying to figure out how to extract words from a string

I would like to create an array of all the words in a string. I tried to Google but only found str_split, which does not separate the words.

php


Solution 1:[1]

You can typically use explode():

$string  = "a bunch of words";
$array_of_words = explode(" ", $string);

http://php.net/manual/en/function.explode.php

Solution 2:[2]

Try using this:

$new_array = explode(' ', $your_string);

Now $new_array contains a string for every word in $your_string.

Solution 3:[3]

I prefer the solution

$string  = "    a   bunch    of  words   ";
$array_of_words = preg_split("/\s/", $string, -1, PREG_SPLIT_NO_EMPTY);

that gives

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(5) "bunch"
  [2]=>
  string(2) "of"
  [3]=>
  string(5) "words"
}

IMO is more elegant.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dflash
Solution 2 Simon M
Solution 3 Suvier