[ACCEPTED]-How can I convert a sentence to an array of words?-split

Accepted answer
Score: 31

You could use explode, split or preg_split.

explode uses a fixed string:

$parts = explode(' ', $string);

while 3 split and preg_split use a regular expression:

$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);

An example 2 where the regular expression based splitting 1 is useful:

$string = 'foo   bar';  // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));
Score: 11
$parts = explode(" ", $str);

0

Score: 4
print_r(str_word_count("this is a sentence", 1));

Results in:

Array ( [0] => this [1] => is [2] => a [3] => sentence )

0

Score: 3

Just thought that it'd be worth mentioning 10 that the regular expression Gumbo posted—although 9 it will more than likely suffice for most—may 8 not catch all cases of white-space. An example: Using 7 the regular expression in the approved answer 6 on the string below:

$sentence = "Hello                       my name    is   peter string           splitter";

Provided me with the 5 following output through print_r:

Array
(
    [0] => Hello
    [1] => my
    [2] => name
    [3] => is
    [4] => peter
    [5] => string
    [6] =>      splitter
)

Where as, when 4 using the following regular expression:

preg_split('/\s+/', $sentence);

Provided 3 me with the following (desired) output:

Array
(
    [0] => Hello
    [1] => my
    [2] => name
    [3] => is
    [4] => peter
    [5] => string
    [6] => splitter
)

Hope 2 it helps anyone stuck at a similar hurdle 1 and is confused as to why.

Score: 1

Just a question, but are you trying to make 2 json out of the data? If so, then you might 1 consider something like this:

return json_encode(explode(' ', $inputString));

More Related questions