vote up 0 vote down star

Using Php. Need:

On String Input: "Some terms with spaces between"
OutputArray <String>: {Some, terms, with, spaces, between}
flag

3 Answers

vote up 9 vote down check

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));
link|flag
Its explode not implode. – Ólafur Waage Mar 6 '09 at 12:47
Do you mean explode? – strager Mar 6 '09 at 12:47
Sure, I meant explode not implode. – Gumbo Mar 6 '09 at 12:49
1  
I mix up those two constantly too. Until the script explodes in my face. – christian studer Mar 6 '09 at 13:20
Do you mean "implodes in my face"? :) – grantwparks Sep 25 at 20:10
vote up 8 vote down
$parts = explode(" ", $str);
link|flag
vote up 1 vote down

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));
link|flag

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.