Jump to content

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);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.