Question

From this string:

$input = "Some terms with spaces between";

how can I produce this array?

$output = ['Some', 'terms', 'with', 'spaces', 'between'];
Was it helpful?

Solution

You could use explode, split or preg_split.

explode uses a fixed string:

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

while split and preg_split use a regular expression:

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

An example where the regular expression based splitting is useful:

$string = 'foo   bar';  // multiple spaces
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));

OTHER TIPS

$parts = explode(" ", $str);
print_r(str_word_count("this is a sentence", 1));

Results in:

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

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

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

Provided me with the following output through print_r:

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

Where as, when using the following regular expression:

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

Provided me with the following (desired) output:

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

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

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

return json_encode(explode(' ', $inputString));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top