2

こんにちは、CSVファイルを取り込んでファイルに挿入する関数を作成しようとしていますが、それを実行する必要はありません。

現時点では、爆発を使用してファイルから行を取得しています..

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');
}
4

3 に答える 3

2

あなたの答えはここにあると思います:

正規表現を使用して文字列を分解する

@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]);

説明:

トリックは、括弧のに一致させることです,

~          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

ネストされた括弧の場合:

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

preg_match_all("~(['#@°]).*?\1|(\((?>[^()]++|(?-1)?)*\))|[^,]++~", $string,$result);
print_r($result[0]);
于 2013-05-10T15:45:22.703 に答える
0

preg_split を PREG_SPLIT_DELIM_CAPTURE オプションとともに使用できます。

$str = field1,field2,field3,field4,"一部のテキスト、その他のテキスト",field6;

それからこのようなもの

$match = preg_split("ypir expression", $str, null, PREG_SPLIT_DELIM_CAPTURE);
于 2013-05-10T12:29:13.850 に答える