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) "" Link to comment https://forums.phpfreaks.com/topic/214275-parsing-csv-need-to-get-null-values/ 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); Link to comment https://forums.phpfreaks.com/topic/214275-parsing-csv-need-to-get-null-values/#findComment-1115098 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. Link to comment https://forums.phpfreaks.com/topic/214275-parsing-csv-need-to-get-null-values/#findComment-1115103 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 Link to comment https://forums.phpfreaks.com/topic/214275-parsing-csv-need-to-get-null-values/#findComment-1115239 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.