I am looking for a regular expression using preg_match_all in PHP 5 that would allow me to split a string by commas, so long as the commas do not exist inside single quotes, allowing for escaped single quotes. Example data would be:
(some_array, 'some, string goes here','another_string','this string may contain "double quotes" but, it can\'t split, on escaped single quotes', anonquotedstring, 83448545, 1210597346 + '000', 1241722133 + '000')
This should produce a match that looks like this:
(some_array
'some, string goes here'
'another_string'
'this string may contain "double quotes" but, it can\'t split, on escaped single quotes'
anonquotedstring
83448545
1210597346 + '000'
1241722133 + '000')
I’ve tried many, many regexes… My current one looks like this, although it doesn’t match 100% correctly. (It still splits some commas inside single quotes.)
"/'(.*?)(?<!(?<!\\\)\\\)'|[^,]+/"
Have you tried
str_getcsv? It does exactly what you need without a regular expression.You can even implement this method in PHP versions older than 5.3, mapping to
fgetcsvwith this snippet from a comment in the docs: