4

希望这是一个简单的过程。我有一个包含 CSV 文件输出的行的数组。我需要做的只是删除出现在双引号之间的任何逗号。

我在正则表达式中磕磕绊绊,遇到了麻烦。这是我看起来很悲伤的代码:

<?php    

$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';

$pattern = '(?<=\")/\,/(?=\")'; //this doesn't work

$revised_input = preg_replace ( $pattern , '' , $csv_input);

echo $revised_input;

//would like revised input to echo: "herp","derp,"hey get rid of these commas man",1234

?>

非常感谢大家。

4

5 回答 5

8

原始答案

您可以使用str_getcsv()它,因为它是专门为处理 CSV 字符串而设计的:

$out = array();
$array = str_getcsv($csv_input);
foreach($array as $item) {
    $out[] = str_replace(',', '', $item);
}

$out现在是一个元素数组,其中没有任何逗号,然后您可以将其内爆,因为删除逗号后将不再需要引号:

$revised_input = implode(',', $out);

更新评论

如果引号对您很重要,那么您可以像这样将它们重新添加:

$revised_input = '"' . implode('","', $out) . '"';

另一种选择是使用其中一个str_putcsv()(不是标准的 PHP 函数)实现在网络上浮动,例如这个

于 2012-05-24T14:06:00.723 回答
2

这是一种非常幼稚的方法,仅当“有效”逗号是引号之间的逗号时才有效,而引号之间可能只有空格。

<?php    

$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';

$pattern = '/([^"])\,([^"])/'; //this doesn't work

$revised_input = preg_replace ( $pattern , "$1$2" , $csv_input);

echo $revised_input;

//ouput for this is: "herp","derp","hey get rid of these commas man",1234

它应该进行更多测试,但它在这种情况下有效。

它可能不起作用的情况是字符串中没有引号。

一、二、三、四 -> onetwothreefour

编辑:更正了删除空格和相邻字母的问题。

于 2012-05-24T14:14:19.523 回答
1

好吧,我并没有偷懒,而是编写了一个小函数来完全满足您的需求:

function clean_csv_commas($csv){
    $len = strlen($csv);
    $inside_block = FALSE;
    $out='';
    for($i=0;$i<$len;$i++){
        if($csv[$i]=='"'){
            if($inside_block){
                $inside_block=FALSE;
            }else{
                $inside_block=TRUE;
            }
        }

        if($csv[$i]==',' && $inside_block){
            // do nothing
        }else{
            $out.=$csv[$i];
        }

    }
    return $out;
}
于 2018-08-02T16:57:30.000 回答
0

你可能是从错误的角度来的。

与其从文本中删除逗号(大概这样您就可以在逗号上拆分字符串以获得单独的元素),不如写一些对引号起作用的东西呢?

找到开头引号后,您可以检查字符串的其余部分;下一个引号之前的任何内容都是此元素的一部分。您也可以在此处添加一些检查以查找转义引号,例如:

"this is a \"quote\""

仍然会被正确阅读。

于 2012-05-24T14:07:59.257 回答
0

不完全是您一直在寻找的答案 - 但我用它来清理 CSV 中数字中的逗号。

$csv = preg_replace('%\"([^\"]*)(,)([^\"]*)\"%i','$1$3',$csv);

"3,120", 123, 345, 567 ==> 3120, 123, 345, 567

于 2018-08-02T16:30:59.863 回答