I get a CSV data from a SOAP call in php. Unfortunately, the data may have commas in it. It is formatted correctly as in
1,name,2,lariat,3,”first, last”,5,NMEA,…
I need to parse it to individual values in either php or javascript. I have browsed through threads on stack overflow and elsewhere but have not found a specific solution in php / javascript.
The approach I am currently using is
$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$pattern = '/,|,"/';
$t2=preg_replace ('/,|(".*")/','$0*',$subject);
$t2=str_replace(',','*',$t2);
$t2=str_replace('*',',',$t2);
Where * is the deliminator, but the preg_replace generates an extra *. I have tried a couple of other approaches involving preg_match and other preg_ functions but did not succeed in having any kind of a clean split.
Any suggestion on how to split up CSV data that contains commas in it?
Don’t attempt to do this with a regular expression. Just use
str_getcsv()! The third parameter informsstr_getcsv()to look for quote-enclosed fields.