webnoob
webnoob

Reputation: 15934

Regex to split a string up on each {space} but not when contained in quotes

I am not very good with regex (in fact don't know much at all). I need to create an array from a string split at the spaces BUT only when the space isn't within double quotes so:

this.line "should be 3" elements

would appear like:

this.line
should be 3
elements

I know I can use preg_match to get the array but I have no clue on the regex.

p.s I have looked at other solutions in Stack Overflow but the regex doesn't seem to work with my preg_match.

Thanks.

Upvotes: 4

Views: 1220

Answers (1)

Mark Byers
Mark Byers

Reputation: 838146

You could try this:

preg_match_all('/"[^"]+"|\S+/', $s, $matches);

See it working online: ideone

Upvotes: 6

Related Questions