PHP preg_split用于逗号但不用双引号

时间:2013-05-10 12:27:00

标签: php regex

您好我正在尝试创建一个接收CSV文件的函数,然后将其插入到文件中,但不是我需要它做的。

目前我正在使用explode来获取文件中的行..

explode(",", $linearray);

这可行,但如果有类似

的话
field1,field2,field3,field4,"some text, some other text",field6

我得到这个数组

array(
[0]=>field1,
[1]=>field2,
[2]=>field3,
[3]=>field4,
[4]=>"some text,
[5]=>some other text",
[6]=>field6
)

这不是我想要的结果。我知道preg_split可以为我做,但我对正则表达式并不擅长。 我想要的结果是。

field1,field2,field3,field4,"some text, some other text",field6

array(
[0]=>field1,
[1]=>field2,
[2]=>field3,
[3]=>field4,
[4]=>some text, some other text,
[5]=>field6
)

请帮忙。

来自PHP CLASS的CSV文件的函数我写了

    $lineseparator = "\n";
    $fieldseparator = "\n";

function ReadFile(){
    $this->csvcontent = fread($this->_file,$this->size);
    fclose($this->_file);
    return ($this->csvcontent)? true : false ;
}
function InsertFileToSQL(){
    $query = "";
    $i_count = 0;
    $queries = "";
    $linearray = array();
    $file_array = explode($this->lineseparator,$this->csvcontent);
    $lines = count($file_array);
    foreach($file_array as $key => $value) {
        $value = trim($value," \t");
        $value = str_replace("\r","",$value);
        /***********************************************************************************************************
        This line escapes the special character. remove it if entries are already escaped in the csv file
        ************************************************************************************************************/
        $value = str_replace("'","\'",$value);
        $value = str_replace("\"","",$value);
        /***********************************************************************************************************/

        $linearray = explode($this->fieldseparator,$value);

        foreach($linearray as $key2 => $value2){
            // Format all fields that match a date format the Reformat for SQL.
            $date = explode("/", $value2);
            if(count( $date ) == 3 ){
                $linearray[$key2] = $date[2]."-".$date[1]."-".$date[0];
            }
        }

        $linemysql = implode("','",$linearray);
        if($linemysql != "" && $linemysql != NULL){
            if($this->csvheader ){
                if($key != 0){
                    if($this->addauto == 1){
                        $query = "INSERT INTO `$this->db_table` VALUES (NULL,'$linemysql');";
                    }else{
                        $query = "INSERT INTO `$this->db_table` VALUES ('$linemysql');";
                    }
                }else{
                    $lines--;
                }
                $insert = mysql_query($query) or die(mysql_error());
                if($insert){
                    $queries .= $query . "\n";
                    $i_count++;
                }

            }else{
                if($this->addauto == 1){
                    $query = "INSERT INTO `$this->db_table` VALUES (NULL,'$linemysql');";
                }else{
                    $query = "INSERT INTO `$this->db_table` VALUES ('$linemysql');";
                }
                $insert = mysql_query($query) or die((mysql_error()." in QUERY: ".$query));
                if($insert){
                    $queries .= $query . "\n";
                    $i_count++;
                }

            }
        }else{
            $this->null_row++;
            $lines--;
        }


    }
    if($this->save) {
        $f = fopen($this->output_location.$this->outputfile, 'a+');

        if ($f) {
          @fputs($f, $queries);
          @fclose($f);
        }else{
            echo("Error writing to the output file.", 'error');
        }

    }
    $lines--;//fix array count
    $text = "";
    if($i_count - $this->null_row  != 0){$i_count = $i_count - $this->null_row ;$text .= "<br>$i_count Records were inserted Successfully.";}
    echo("Found a Total of $lines Record(s) in this csv file.<br>$this->null_row Record(s) were/are Blank or Null.$text", 'success');
}

3 个答案:

答案 0 :(得分:1)

我认为你的答案就在这里:

exploding a string using a regular expression

正如 @Casimir et Hippolyte 在该页面中所说:

您可以使用preg_match_all

完成工作
$string="a,b,c,(d,e,f),g,'h, i j.',k";

preg_match_all("~'[^']++'|\([^)]++\)|[^,]++~", $string,$result);
print_r($result[0]);

说明:

诀窍是在<{1}} 之前匹配括号

,

如果您有多个分隔符(如引号(打开和关闭时相同)),您可以使用捕获组编写这样的模式:

~          Pattern delimiter
'
[^']       All charaters but not a single quote
++         one or more time in [possessive][1] mode
'
|          or
\([^)]++\) the same with parenthesis
|          or
[^,]       All characters but not a comma
++
~

说明:

$string="a,b,c,(d,e,f),g,'h, i j.',k,°l,m°,#o,p#,@q,r@,s";

preg_match_all("~(['#@°]).*?\1|\([^)]++\)|[^,]++~", $string,$result);
print_r($result[0]);

使用嵌套括号:

(['#@°])   one character in the class is captured in group 1
.*?        any character zero or more time in lazy mode 
\1         group 1 content

答案 1 :(得分:0)

您可以将preg_split与PREG_SPLIT_DELIM_CAPTURE选项一起使用。

$ str = field1,field2,field3,field4,“some text,some other text”,field6;

然后就是这样的

$match = preg_split("ypir expression", $str, null, PREG_SPLIT_DELIM_CAPTURE);

答案 2 :(得分:0)

我不会回答被问到的问题,因为他要求错误解决他的问题。但是,我希望这个解决方案对他来说更好:

查看问题中的代码,OP基本上是通过PHP读取CSV文件并将其导入mysql数据库。

MySQL实际上提供了一种直接用它的LOAD DATA INFILE语法执行此操作的方法,而不必在PHP中解析文件。它比通过PHP处理它快得多,并且完全避免了OP所具有的整个问题。

在PHP中,您只需执行以下操作:

$query = <<<eof
  LOAD DATA INFILE {$filename} INTO {$table}
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES
  field1, field2, field3, field4, field5, field6
eof;
mysqli_query($conn, $query);

您可能需要为代码中的一些更复杂的内容修改该查询(即转换日期格式等),但是一旦您掌握了LOAD DATA INFILE语法,就可以了。我会发现合并相当简单。

我希望有所帮助。

相关问题