javascript 处理CSV中的逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6536826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:59:54  来源:igfitidea点击:

Dealing with commas in CSV

phpjavascriptregexsoapcsv

提问by Lord Loh.

I get a CSV data from a SOAP call in php. Unfortunately, the data may have commas in it. It is formatted correctly as in

我从 php 中的 SOAP 调用获得了一个 CSV 数据。不幸的是,数据中可能有逗号。它的格式正确,如

1,name,2,lariat,3,"first, last",5,NMEA,...

1,name,2,lariat,3,"first, last",5,NMEA,...

I need to parse it to individual values in either php or javascript. I have browsed through threads on stack overflow and elsewhere but have not found a specific solution in php / javascript.

我需要在 php 或 javascript 中将其解析为单个值。我浏览了堆栈溢出和其他地方的线程,但没有在 php/javascript 中找到特定的解决方案。

The approach I am currently using is

我目前使用的方法是

$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$pattern = '/,|,"/';
$t2=preg_replace ('/,|(".*")/','
$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$array = str_getcsv($subject, ",", '"');

print_r($array);
// Prints:
Array
(
    [0] => 123
    [1] => name
    [2] => 456
    [3] => lryyrt
    [4] => 123213
    [5] => first,last
    [6] => 8585
    [7] => namea3
)
*',$subject); $t2=str_replace(',','*',$t2); $t2=str_replace('*',',',$t2);

Where * is the deliminator, but the preg_replacegenerates an extra *. I have tried a couple of other approaches involving preg_matchand other preg_functions but did not succeed in having any kind of a clean split.

其中 * 是分隔符,但会preg_replace生成一个额外的 *。我尝试了其他几种涉及preg_match和其他preg_功能的方法,但没有成功地进行任何类型的清晰拆分。

Any suggestion on how to split up CSV data that contains commas in it?

关于如何拆分包含逗号的 CSV 数据的任何建议?

回答by Michael Berkowski

Don't attempt to do this with a regular expression. Just use str_getcsv()! The third parameter informs str_getcsv()to look for quote-enclosed fields.

不要尝试使用正则表达式执行此操作。就用str_getcsv()!第三个参数通知str_getcsv()查找引号括起来的字段。

<?php
//
// Convert csv file to associative array:
//

function csv_to_array($input, $delimiter=',')
{
    $header = null;
    $data = array();
    $csvData = str_getcsv($input, "\n");

    foreach($csvData as $csvLine){
        if(is_null($header)) $header = explode($delimiter, $csvLine);
        else{

            $items = explode($delimiter, $csvLine);

            for($n = 0, $m = count($header); $n < $m; $n++){
                $prepareData[$header[$n]] = $items[$n];
            }

            $data[] = $prepareData;
        }
    }

    return $data;
}

//-----------------------------------
//
//Usage:

$csvArr = csv_to_array(file_get_contents('test.csv'));

?>

回答by Pheonix

Just another way to convert a csv file to an associative array.

将 csv 文件转换为关联数组的另一种方法。

$.csv.toArray(csv);

回答by Evan Plaice

For JavaScript use jQuery-CSV

对于 JavaScript 使用jQuery-CSV

If you're already using jQuery, just add the jquery-csv.js module to expose the extension methods. Then just convert the CSV directly to a JavaScript array.

如果您已经在使用 jQuery,只需添加 jquery-csv.js 模块以公开扩展方法。然后只需将 CSV 直接转换为 JavaScript 数组。

If you're only parsing the following will convert it to a one-dimensional array:

如果您只解析以下内容,则会将其转换为一维数组:

$.csv.toArrays(csv);

If you have a multi-line CSV string the following will convert it to a two-dimensional array:

如果您有一个多行 CSV 字符串,以下内容会将其转换为二维数组:

##代码##

Note: all the different line endings are detected and split correctly using a smart regex.

注意:使用智能正则表达式检测并正确拆分所有不同的行尾。

The default delimiter is a double-quote (") and the default separator is a comma (,) but you can change use custom settings by specifying them in the method call.

默认分隔符是双引号 ("),默认分隔符是逗号 (,),但您可以通过在方法调用中指定来更改使用自定义设置。

Ex:

前任:

$.csv.toArray(csv, { separator:';', delimiter:"'" });

$.csv.toArray(csv, { 分隔符:';', 分隔符:"'" });

I created the project to provide an end-to-end CSV parser written in JavaScript that takes the guesswork out of importing-exporting CSV.

我创建了这个项目来提供一个用 JavaScript 编写的端到端 CSV 解析器,它消除了导入-导出 CSV 的猜测。

Doing the heavy lifting on the client removes unnecessary load on the server and removes any unnecessary AJAX round-trips to the server.

在客户端上执行繁重的工作可以消除服务器上不必要的负载,并消除到服务器的任何不必要的 AJAX 往返。

Update:

更新:

If you're looking for a server-side solution, the library also works on Node.js.

如果您正在寻找服务器端解决方案,该库也适用于 Node.js。