【问题标题】:Regex for wrong quoted CSV-File引用错误的 CSV 文件的正则表达式
【发布时间】:2018-04-18 09:51:55
【问题描述】:

我遇到了一些损坏的 csv 文件的问题。我是这样理解的:

column1,column2,column3,column4,column5,column6
123,"some text",""column3 text"",""still column3 text"",4,234,""
123,"some text",""column3 text"",4,234,""

在表格中应该是这样的:

column1 | column2   | column3                            | column4 | column5 | column6
123     | some text | "column3 text, still column3 text" | 4       | 234     | 
123     | some text | "column3 text"                     | 4       | 234     |

我正在使用 php 读取文件并尝试将它与 str_getcsv 一起使用到数组中。但是由于这个断引号,它不起作用,并且总是比标题多列。

我根本不需要第 3 列的值,所以我尝试做一些正则表达式来创建三个组,然后做 preg_replace。但我没有得到适用于这两行的正则表达式。

有了这个正则表达式,我只得到第一行:https://regex101.com/r/OjTAAC/1

这样我就得到了第二行:https://regex101.com/r/I2xqPs/1

任何人都对如何获得适用于这两种情况的正则表达式有一些帮助?

【问题讨论】:

  • 肯定有别的办法,this regex好像太麻烦了。
  • 最后的空""会出问题
  • 您可以根据逗号的数量拆分行并逐个执行正则表达式
  • 我认为该文件太损坏了,无法理解。我的意思是除了你说“仍然是第 3 列”这一事实之外,还有什么规则说它仍然是第 3 列?
  • 还有一个excel导出,第3列的值是'"column3 text,还是column3 text"'。但在 CSV-Export 中,它看起来像 ' ""column3 text"",""still column3 text"" '。我知道它完全坏了。但我不能等到它被修复。

标签: php regex csv preg-match


【解决方案1】:

可能有更简单的解决方案,但我会备份或拥有文件的副本,但你可能不得不做不同的事情,因为它很大。

让我们尝试一些不同的东西

//$str = '123,"some text",""column3 text"",""still column3 text"",4,234,""';
//$str = '123,"some text",""column3 text"",4,234,""'

while (($str = fgets($handle, 4096)) !== false) {      
     $str = str_replace('"', '', $str);
    $line = explode(',',$str);

    //combine line item 2,3
    if(count($line) == 7 ){
        $line[2] .= ', '.$line[3];
        //remove item 3
        unset($line[3]);
        $line = array_values($line);
    } 
    print_r( $line );
}

只要线条与您展示的内容一致,它应该可以工作。

$array =[
    '123,"some text",""column3 text"",""still column3 text"",4,234,""',
    '123,"some text",""column3 text"",4,234,""'
];

foreach($array as $str){
    $str = str_replace('"', '', $str);
    $line = explode(',',$str);

    //combine line item 2,3
    if(count($line) == 7 ){
        $line[2] .= ', '.$line[3];
        //remove item 3
        unset($line[3]);
        $line = array_values($line);
    } 
    print_r( $line );
}

输出

Array
(
    [0] => 123
    [1] => some text
    [2] => column3 text, still column3 text
    [3] => 4
    [4] => 234
    [5] =>
)
Array
(
    [0] => 123
    [1] => some text
    [2] => column3 text
    [3] => 4
    [4] => 234
    [5] =>
)

你可以在这里测试它。

http://sandbox.onlinephpfunctions.com/code/f39eb94ccef045213a30385cc7daa326ce3aa25d

【讨论】:

  • 嘿,谢谢你的回答,但我的问题不是行尾的“”。它是 CSV 文件中完全损坏的 Column3 值。
  • 正如我所说,在我的回答中,行尾的"" 是完全有效的。只要没有有效的双引号"",我输入的内容就会起作用,最后一个是有效双引号的示例。
  • 是的,这将是一个可行的解决方案。替换所有“”的想法我还没有。我的解决方法目前看起来像这样sandbox.onlinephpfunctions.com/code/…
  • 是的," 在这种情况下大部分都是垃圾。
猜你喜欢
  • 2014-01-19
  • 1970-01-01
  • 2012-06-28
  • 2011-03-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
相关资源
最近更新 更多