How can I break a string up by spaces in PHP, respecting quoted sub strings? I think there must be some command to parse this type of string like arguments but I don’t know what that is.
Example string:
$string = '12345 abcd "hello world" defgh "nice to meet you" 34554';
I normally use one of these three to break up strings. But I don’t think they have the capability to break the string up like I’m suggesting.
$result = str_replace(' ',"\n",$string);
$result = explode(' ',$string);
$result = preg_replace('#\s#',"\n",$string);
Outcome:
12345
abcd
"hello
world"
defgh
"nice
to
meet
you"
34554
Desired outcome:
12345
abcd
hello world
defgh
nice to meet you
34554
UPDATE
I guess I was impressed with PHP’s parse_str command to deal with URL query variables and was hoping PHP had something I that could work for this example, sort of like getopt does for the command line arguments.
You can use fgetcsv() / str_getcsv() for this.
prints