Jump to content

Parsing CSV - Need to get null values


colinzeal109

Recommended Posts

I am parsing a CSV file that has long strings with commas contained within quotes and I found the following RegEx.  It does exactly what I need, however, blank fields are skipped.  I need it to put a null value in the placeholder.

 

preg_match_all("/\"[^\"]+\"|[^,]+/", $input, $output);

 

Example of $input:

1,"Test record",,"Comma contained, within field"

 

After running the RegEx, the var_dump would be:

array(3) { [0]=> string(1) "1" [1]=> string(11) "Test record" [2]=> string(29) "Comma contained, within field" } 

 

I need it to be where [1] => string(0) ""

Link to comment
https://forums.phpfreaks.com/topic/214275-parsing-csv-need-to-get-null-values/
Share on other sites

You mean you want

[2] => string(0) ""

 

The poblem is that the plus sign (+) will match 1 or more instances. So, a non-comma has to exist between commas. Instead you want to match none or more. Try this:

 

preg_match_all("/\"[^\"]*\"|[^,]*/", $input, $output);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.