如果您的 CSV 文件是正确的(每个字段以“开头和结尾”或不包含“”,那么您可以使用递归函数解析字符串,如下所示:
$csvString = 'zero,"o,ne",two,"thr,ee"';
function parseCsv($string, &$result)
{
$regex = '/^((".*")|([^"].*))(,(.*))?$/U';
$matches = array();
preg_match($regex, $string, $matches);
$result[] = $matches[1];
if(isset($matches[5]))
{
parseCsv($matches[5], $result);
}
}
$result = array();
parseCsv($csvString, $result);
var_dump($result);
请注意,这尚未使用包含(转义)引号的带引号的字符串进行测试。它还保留引用字符串周围的引号。
上述函数的结果是
array
0 => string 'zero' (length=4)
1 => string '"o,ne"' (length=6)
2 => string 'two' (length=3)
3 => string '"thr,ee"' (length=8)