Regular expression for parsing CSV in PHP

前端 未结 6 2210
离开以前
离开以前 2020-12-10 06:58

I already managed to split the CSV file using this regex: \"/,(?=(?:[^\\\"]\\\"[^\\\"]\\\")(?![^\\\"]\\\"))/\"

But I ended up with an array of stri

6条回答
  •  情歌与酒
    2020-12-10 07:16

    I agree with the others who said you should use the fgetcsv function instead of regexes. A regex may work okay on well-formed CSV data, but if the CSV is malformed or corrupt, the regex will silently fail, probably returning bogus results in the process.

    However, the question was specifically about stripping unwanted quotation marks after the initial split. The one proposed solution (so far) is too naive, and it only deals the escaped quotes inside a field, not the actual delimiters. (I know the OP didn't ask about those, but they do need to be removed, so why not do them at the same as the others?) Here's my solution:

    $csv_field = preg_replace('/"(.|$)/', '\1', $csv_field);
    

    This regex matches a quotation mark followed by any character or by the end of the string, and replaces the matched character(s) with the second character, or with the empty string if it was the $ that matched. According to the spec, CSV fields can contain line separators; that doesn't seem to happen much, but you can add the 's' modifier to the regex if you need to.

提交回复
热议问题