用于解析CSV行的PHP正则表达式[重复]

问题描述 投票:-1回答:1

使用: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数组应包含所有字符串值,且不包含双引号字符串括起来的字符。

非常感谢您提供使用正确正则表达式的任何帮助。

php regex preg-match-all
1个回答
0
投票

根据iainn的建议,我尝试了str_getcsv,它确实起作用了!

这里是答案:

$m = str_getcsv($s, ",", "\"");
© www.soinside.com 2019 - 2024. All rights reserved.