【问题标题】:CSV remove commas in quotation marks with regexpCSV使用正则表达式删除引号中的逗号
【发布时间】:2012-01-27 14:05:14
【问题描述】:

我有一个 CSV 文件,我们知道 excel 通过将逗号括在双引号中来在字段中使用逗号,例如我有一个文件

Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB

如何使用 RegExp 将引号替换为“。”相反,但只在引号内,所以我得到了

Product Name,Product Code
Product 1,AAA
Prod.A.B,BBB

作为输出

【问题讨论】:

  • 为什么需要这样做? PHP 的 CSV 处理函数能够使用可选的引号括起来的字段。
  • 我直接从转换为文本 blob 字段的数据库中读取我的 csv,我不想将其写入光盘
  • 原来 PHP 的 CSV 函数很好,但请确保正确编码文件,不能与 UTF8 编码的引号一起正常工作

标签: php regex csv


【解决方案1】:

CSV 处理函数(fgetcsv()fputcsv())在这方面要好得多 - 它们可以处理边缘情况,并且可能比您想出的任何正则表达式更可靠。

// Open the file
$fp = fopen($pathToCsvFile, 'r+');

// Create an array of modified data
$tmp = array();
while (($row = fgetcsv($fp, 8192)) !== FALSE) {
  foreach ($row as &$field) $field = str_replace(',', '.', $field);
  $tmp[] = $row;
}

// Truncate the file and put the pointer at the beginning
ftruncate($fp, 0);
rewind($fp);

// Write the modified data back and close the file
foreach ($tmp as $row) {
  fputcsv($fp, $row);
}
fclose($fp);

编辑根据您关于不想读取/写入磁盘的评论,您可以这样做:

// Lets say the raw CSV data is held in this variable as a string
$rawCsvData = 'Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB';

// Open a virtual file pointer to memory and fill it with your data
$fp = fopen('php://memory', 'w+');
fwrite($fp, $rawCsvData);

// Start from the beginning of the pointer
rewind($fp);

// ... INSERT CODE FROM ABOVE HERE (minus the fopen()/fclose())

$modifiedCsvData = stream_get_contents($fp);
fclose($fp);

【讨论】:

    【解决方案2】:

    这将进行多次替换,并删除引号。

    <?php
    $data = 'Product Name,Product Code
    Product 1,AAA
    "Prod,A,B",BBB';
    
    $rgx = '/"(.+?)"/';
    
    preg_match_all($rgx, $data, $matches);
    $x = 0; $max = count($matches[0]);
    while($x < $max){
        $replace = str_replace(",", ".", $matches[1][$x]);
        $data = str_replace($matches[0][$x], $replace, $data);
        $x++;
    }
    echo $data;
    ?>
    

    【讨论】:

    • 效果很好!对于其他人,如果此页面上没有任何内容,请确保您的文件具有正确的编码
    • @Akshat 效果很好 - 直到该值还包含双引号。然后它会中断,因为正则表达式不考虑转义。这就是为什么 CSV 处理函数是执行此操作的方法 - 您所做的任何事情都无法像它们那样处理边缘情况。
    猜你喜欢
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2016-01-24
    • 2013-01-13
    • 1970-01-01
    • 2016-11-13
    相关资源
    最近更新 更多