使用:PHP 7
我需要从CSV文件中解析一个字符串,然后将其返回到数组中。我正在使用preg_match_all,但到目前为止还没有运气。
这是字符串:
"494","1","41","2009-05-18","NULL","0","3","JONES,ZACK ZX",""
这是PHP代码:
<?php
$s = '"494","1","41","2009-05-18","NULL","0","3","JONES,ZACK ZX",""' ;
$p = '(?<=^|,)(?:[^,"]+|")?(?=,|$)|(?<=^|,)".*?"(?=,|$)';
$m = Array();
$e = preg_match_all($p, $s, $m);
执行后,$m
数组应包含所有字符串值,且不包含双引号字符串括起来的字符。
非常感谢您提供使用正确正则表达式的任何帮助。
根据iainn的建议,我尝试了str_getcsv
,它确实起作用了!
这里是答案:
$m = str_getcsv($s, ",", "\"");