用CSV处理逗号 [英] Dealing with commas in CSV
问题描述
我从php中的SOAP调用中获取CSV数据。不幸的是,数据中可能包含逗号。它格式正确,如
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
1,name,2,lariat,3,first,last,5,NMEA,...
1,name,2,lariat,3,"first, last",5,NMEA,...
我需要在php或javascript中将其解析为单个值。我浏览了堆栈溢出和其他地方的线程,但没有在php / javascript中找到特定的解决方案。
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.
我目前使用的方法是
$subject = '123,name,456,lryyrt,123213,"first,last",8585,namea3';
$pattern = '/,|,"/';
$t2=preg_replace ('/,|(".*")/','$0*',$subject);
$t2=str_replace(',','*',$t2);
$t2=str_replace('*',',',$t2);
其中*是分隔符,但 preg_replace
会产生额外的*。我试过一对涉及 preg_match
和其他 preg _
函数的其他方法,但没有成功进行任何类型的清除拆分。
Where * is the deliminator, but the preg_replace
generates an extra *. I have tried a couple of other approaches involving preg_match
and other preg_
functions but did not succeed in having any kind of a clean split.
有关如何拆分包含逗号的CSV数据的任何建议吗?
Any suggestion on how to split up CSV data that contains commas in it?
推荐答案
不要尝试使用正则表达式。只需使用 str_getcsv()
!第三个参数通知 str_getcsv()
查找引用括号的字段。
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.
$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
)
这篇关于用CSV处理逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!