phpregexcsvreplacepreg-replace

Replace commas not inside single quotes with an @ symbol


Why does my regex pattern not replace all commas with @ except the one in 'location, state'?

$test = preg_replace("#([^ ])([,])([^ ])#","$1@$3","100,,,'test','two',,'location, state',,[],1")

Expected: 100@@@'test'@'two'@@'location, state'@@[]@1

Actual: 100@,,'test'@'two'@,'location, state'@,[]@1

I think it is because the consecutive commas are matched in the pattern. How do I get it to continue from the start of the matched character to include all commas?


Solution

  • Use this one:

    preg_replace('/(?<!\s),(?!\s)/', '@', "100,,,'test','two',,'location, state',,[],1")