2

I'm trying to use preg_split() but the results aren't what I expect to get from the function.

I'm new to php and the whole preg_split() scene and it seems to complicated for me to understand, at least for the moment.

$row = "EL10,40,2019-02-06,55555,2019-01-06,ar@email.com,"Text , random text , 52555885/ 48484848484",Yes,One Two,Broke,2019-01-01,000.00,0.00,0.0,0.0,0.0,0.00,0.00,0.0,VRA "Morning";

$row_expl = preg_split('/(?:[^"]*"|)\K\s*(,\s*|$)/',$row);

I expect to remove comma delimiters while leaving commas in quotation marks.

Everything almost seems to work, the only problem occurs at the very end. It adds extra quotation marks to: VRA "Morning". The result seems like this: "VRA ""Morning"""

brombeer
  • 8,716
  • 5
  • 21
  • 27

1 Answers1

1

A regex actually is the wrong tool for your problem. A CSV parser that defines the delimiter and enclosure character is the tool you need.

str_getcsv('EL10,40,2019-02-06,55555,2019-01-06,ar@email.com,"Text , random text , 52555885/ 48484848484",Yes,One Two,Broke,2019-01-01,000.00,0.00,0.0,0.0,0.0,0.00,0.00,0.0,VRA "Morning')

The default delimiter for the str_getcsv is , and the enclosure character is " so should be all set with the default options. You can see more about the function here http://php.net/manual/en/function.str-getcsv.php.

https://3v4l.org/GFWkr

user3783243
  • 5,368
  • 5
  • 22
  • 41