colinzeal109 Posted September 24, 2010 Share Posted September 24, 2010 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) "" Quote Link to comment Share on other sites More sharing options...
Psycho Posted September 24, 2010 Share Posted September 24, 2010 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); Quote Link to comment Share on other sites More sharing options...
salathe Posted September 24, 2010 Share Posted September 24, 2010 For what it's worth str_getcsv was (literally) written for this purpose. Quote Link to comment Share on other sites More sharing options...
colinzeal109 Posted September 24, 2010 Author Share Posted September 24, 2010 i just put a str_replace ahead of it: $input = str_replace(",,",", ,",$input); it seems to get the results i need. thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.