regex - PHP preg_split for commas but not in double quotes -


hi im trying make function takes in csv file insert file whitch works not need do.

at moment using explode rows file..

explode(",", $linearray); 

this workes if there like

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

i array

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

which not outcome want. know preg_split can me im not @ regular expressions. outcome want is.

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

please help.

functions csv file php class have written

    $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 $key => $value) {         $value = trim($value," \t");         $value = str_replace("\r","",$value);         /***********************************************************************************************************         line escapes special character. remove if entries escaped in csv file         ************************************************************************************************************/         $value = str_replace("'","\'",$value);         $value = str_replace("\"","",$value);         /***********************************************************************************************************/          $linearray = explode($this->fieldseparator,$value);          foreach($linearray $key2 => $value2){             // format fields match date format reformat 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 `$this->db_table` values (null,'$linemysql');";                     }else{                         $query = "insert `$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 `$this->db_table` values (null,'$linemysql');";                 }else{                     $query = "insert `$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 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 inserted successfully.";}     echo("found total of $lines record(s) in csv file.<br>$this->null_row record(s) were/are blank or null.$text", 'success'); } 

i think answer in here:

exploding string using regular expression

as @casimir et hippolyte has said in page:

you can job using preg_match_all

$string="a,b,c,(d,e,f),g,'h, j.',k";  preg_match_all("~'[^']++'|\([^)]++\)|[^,]++~", $string,$result); print_r($result[0]); 

explanation:

the trick match parenthesis before ,

~          pattern delimiter ' [^']       charaters not single quote ++         1 or more time in [possessive][1] mode ' |          or \([^)]++\) same parenthesis |          or [^,]       characters not comma ++ ~ 

if have more 1 delimiter quotes (that same open , close), can write pattern this, using capture group:

$string="a,b,c,(d,e,f),g,'h, j.',k,°l,m°,#o,p#,@q,r@,s";  preg_match_all("~(['#@°]).*?\1|\([^)]++\)|[^,]++~", $string,$result); print_r($result[0]); 

explanation:

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

with nested parenthesis:

$string="a,b,(c,(d,(e),f),t),g,'h, j.',k,°l,m°,#o,p#,@q,r@,s";  preg_match_all("~(['#@°]).*?\1|(\((?>[^()]++|(?-1)?)*\))|[^,]++~", $string,$result); print_r($result[0]); 

Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -