[英]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?
有人能指出我正确的方向吗?
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.