Skip to content
Advertisement

PHP split comma-separated values but retain quotes

I’m trying to split a string that contains comma-separated set of values. This can be achieved simply by using str_getcsv but I have an additional requirement where it falls short of. I need to retain quotes.

With an input string of:

JavaScript

I tried two approaches:

explode

JavaScript

Which results in

JavaScript

str_getcsv

JavaScript

This one results in

JavaScript

I prefer using str_getcsv because it splits the values properly but it trims the enclosing quotes out. I need those quotes so I’m hoping I could call the function without it automatically removing the quotes.

Additional Info

I am actually open for a regex solution but I am clueless in that area.


I tried the solution here and it didn’t work.

Advertisement

Answer

This pushed the limits of my regex knowledge, and I was unable to come up with an elegant regex which covers all possible cases for the input string (e.g. If the string ends with a comma) without leaving empty matches at the end.

JavaScript

By itself, this gives:

JavaScript

And you can clean up the empty elements like this:

JavaScript

Note: The regex trims white-space from the start/end of each match. Remove the s* parts if you don’t want that.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement