tags:

views:

1377

answers:

4

Using Php. Need:

On String Input: "Some terms with spaces between"
OutputArray <String>: {Some, terms, with, spaces, between}
+8  A: 
$parts = explode(" ", $str);
Can Berk Güder
+13  A: 

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));
Gumbo
Its explode not implode.
Ólafur Waage
Do you mean explode?
strager
Sure, I meant `explode` not `implode`.
Gumbo
I mix up those two constantly too. Until the script explodes in my face.
christian studer
Do you mean "implodes in my face"? :)
grantwparks
The split function is deprecated in php 5.3 so use explode or preg_split instead
Dimitri
+1  A: 

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));
Cory Collier
A: 
print_r(str_word_count("this is a sentence", 1));

Results in:

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