Felipe Schenone Felipe Schenone - 6 months ago 28
PHP Question

Match everything that isn't a comma followed by a space

There are many similar questions, but none I found addresses exactly my case and I've been trying and trying with no luck.

I have a comma separated lists of values like so:

Apple, Banana, Carrot and Durian, Eggs

So some values are simple words, and others have multiple words. I need to wrap each value with a pair of quotes, and I found an answer that got me pretty close:

preg_replace( $list, '/([^,]+)/g', '"$1"' )

This generates:

"Apple","Banana","Carrot and Durian","Eggs"

But there is a problem: it removes the spaces after the commas. If I add the whitespace character
it doesn't remove the spaces after the commas anymore, but it matches the spaces inside the values:

"Apple", "Banana", "Carrot" "and" "Durian", "Eggs"

Live version at https://regex101.com/r/eN2hY4/31

Thanks a lot in advance!


Use \K to discard previously matched characters.