简体   繁体   English

PHP:如何在多列行中删除双引号内的逗号?

[英]PHP: How can I get rid of commas inside double quotes in a multiple column row?

I need a PHP solution to get rid of commas inside double quotes. 我需要一个PHP解决方案来摆脱双引号内的逗号。 I can't seem to figure out a solution using preg_replace . 我似乎无法找到使用preg_replace的解决方案。

I'm inserting data into a database from a text file that is coma delimited. 我正在从昏迷分隔的文本文件中将数据插入数据库。

Certain columns from the text file contain multiple words that are surrounded in double quotes. 文本文件中的某些列包含多个用双引号括起来的单词。 Theses double quotes have comas inside, so when I attempt to insert the text into my database using coma delimited columns it reads in the quotes between the double quotes and turns them into columns. 这些双引号内部有逗号,所以当我尝试使用逗号分隔列将文本插入我的数据库时,它会读取双引号之间的引号并将它们转换为列。

Here is how a row in the text file looks: 以下是文本文件中的行的外观:

partname,2035, "this is, desc,ription",qty, "another, description",

this is what happens when I attempt to separate it: 当我尝试将它分开时会发生这种情况:

results partname, 2035, this is, desc, ription, qty, another, description,

this is what I want: 这就是我要的:

partime, 2035, this is description, qty, another description,

As you can see, the parts surrounded in double quotes should not be split into separate columns. 如您所见,用双引号括起来的部分不应拆分为单独的列。 I don't know how to fix this; 我不知道如何解决这个问题; could someone point me in the right direction? 有人能指出我正确的方向吗?

Guys, PHP already has a function for this, fgetcsv (get comma sepparated values from files) 伙计们,PHP已经有了这个函数, fgetcsv (从文件中获取逗号的sepparated值)

<?php
$r = array();
$fh = fopen('test.txt','r');
while($t = fgetcsv($fh)) {
    $r[] = $t;
}
var_dump($r);

Which is there since the PHP4 era. 自PHP4时代以来就是这样。

function csv_string_to_array($str){
$expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
$results=preg_split($expr,trim($str));
return preg_replace("/^\"(.*)\"$/","$1",$results);
}

That does the trick. 这就是诀窍。

What you want is the str_getcsv() function. 你想要的是str_getcsv()函数。 It's only available in PHP5.3.0+ though. 它仅适用于PHP5.3.0 +。

Try this function to split a single line into raw values. 尝试使用此函数将单行拆分为原始值。 It tries to cope with pretty irregular CSVs 它试图处理非常不规则的CSV

function csv_split( $src, $comma = ',', $esc = '\\' ){
    $a = array();
    while( $src ){
        $c = $src{0};
        switch( $c ){
        // permit empty values
        case ',':
            $a[] = '';
            $src = substr( $src, 1 );
            continue 2;
        // ignore whitespace
        case ' ':
        case "\t":
            preg_match('/^\s+/', $src, $r );
            $src = substr( $src, strlen($r[0]) );
            continue 2;
        // quoted values
        case '"':
        case "'":
        case '`':
            $reg = sprintf('/^%1$s((?:\\\\.|[^%1$s\\\\])*)%1$s\s*(?:,|$)/', $c );
            break;
        // naked values
        default:
            $reg = '/^((?:\\\\.|[^,\\\\])*)(?:,|$)/';
            $c = ',';
        }
        if( preg_match( $reg, $src, $r ) ){
            $a[] = empty($r[1]) ? '' : str_replace( '\\'.$c, $c, $r[1] );
            $src = substr( $src, strlen($r[0]) );
            continue;
        }
        // else fail
        trigger_error("csv_split failure", E_USER_WARNING );
        break;
    }
    return $a;
}

This may work for you: 这可能对你有用:

$pieces = explode( '"', 'partname,2035, "this is, desc,ription",qty, "another, description",' );

// explode the ones we should split (will be even-# elements)
for ( $i=0; $i<= count($pieces); $i+=2 ) {
    $tmpArray   = explode(",", $pieces[$i]);
    foreach($tmpArray as $value) {
        if ( strlen(trim($value)) > 0 ) {
            $finalArray[] = $value;
        }
    }
}

// now add the ones we shouldn't split inside quotes (odd-# elements)
for ( $i=1; $i<= count($pieces); $i+=2 ) {
    if ( strlen(trim($pieces[$i])) > 0 ) {  
        $finalArray[] = $pieces[$i];
    }
}

// show the result
echo "<pre>";
print_r($finalArray);
echo "<pre>";

The general solution for the problem would be to escape the separator character while creating the line before assembling the coma separated data with a simple. 该问题的一般解决方案是在用简单组合彗差分离数据之前在创建线时转义分隔符。

define(SEPARATOR,',');
$dataField = str_replace(SEPARATOR,'BSLASH'.SEPARATOR,$dataField);

Pls change BSLASH to backslash character (the comment input box is more intelligent than me as it behaves strangely when I try to write a backslash character and I can't figure out how to turn it off :) ) 请将BSLASH更改为反斜杠字符(注释输入框比我更聪明,因为当我尝试编写反斜杠字符时它表现得很奇怪,我无法弄清楚如何将其关闭:))

Of course it's not an option if you receive the data from 3rd party source. 当然,如果您从第三方来源收到数据,则无法选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用php解析CSV,但忽略字符串中的逗号和双引号 - How can I parse a CSV with php but ignore the commas and double quotes in the strings PHP数组到json,如何摆脱一些双引号? - PHP Array to json, how to get rid of some double quotes? 如何摆脱PHP JSON字符串中的反斜杠和双引号 - How do I get rid of backslashes and double quotes in php json string 如何在PHP中删除双引号之间的逗号 - How to remove commas between double quotes in PHP PHP:如何用逗号分解字符串,但不是逗号在引号内? - PHP: How can I explode a string by commas, but not wheres the commas are within quotes? 如何在字符串 PHP 中的双引号后添加逗号? - How to add commas after double quotes in string PHP? 如何在PHP的ajax JSON响应中将双引号放在字符串中? - How can I put double quotes inside a string within an ajax JSON response from php? 我如何在带有双引号的 php 查询中使用 MsSQL Where CONTAINS? - How can i use MsSQL Where CONTAINS inside a php query with double quotes? 如何用逗号分隔字符串,但不能用逗号括起来(?»)引号? - How can I explode a string by commas, but not where the commas are within this («») quotes? 在Postgres中,使用fetchAll(PDO :: FETCH_NUM)。 如何摆脱双引号? - In Postgres, using fetchAll(PDO::FETCH_NUM). How do I get rid of the Double quotes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM