TeAmEr
TeAmEr

Reputation: 4773

PHP get comma separated values which are not enclosed

having string like this :

5, "hi all, this is a comma", 'text without comma', 5,'a',',',","

i want to break the string into an array, but still there are values which contain commas (enclosed by single OR double quotes)

what's the fastest regex possible (explode won't work here)

i could use str_getcsv but the strings are enclosed sometime by single quotes , other times by double quotes ! need something smarter

Upvotes: 2

Views: 457

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can use a csv parser, or preg_split with this pattern:

$pattern = '~(?:\'[^\']*\'|"[^"]*"|)\K(,|$)~';

Upvotes: 3

Related Questions