Regular expression for parsing CSV in PHP

前端 未结 6 2217
离开以前
离开以前 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:15

    For those of you who wan't to use regex instead of fgetcsv. Here is a complete example how to create a html table from csv using a regex.

        $data = file_get_contents('test.csv');
        $pieces = explode("\n", $data);
    
        $html .= "\n";
        foreach (array_filter($pieces) as $line) {
    
                $html .= "\n";
                $keywords = preg_split('/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/', $line,-1,PREG_SPLIT_DELIM_CAPTURE);
    
                foreach ($keywords as $col) {
                        $html .= "\n";
                }
                $html .= "\n";
        }
        $html .= "
    ".trim($col, '"')."
    \n";

提交回复
热议问题