拆分以逗号分隔的字符串(包含也包含逗号的值)

时间:2011-08-24 22:51:58

标签: php preg-replace explode

  

可能重复:
  An explode() function that ignores characters inside quotes?

我有一个示例问题。这是

$str = 'field0,field1,field2,"field3a,field3b,field3c",field4,"field5"';

我想将该字符串分解为像这样的数组

$arr[0] = 'field0';
$arr[1] = 'field1';
$arr[2] = 'field2';
$arr[3] = 'field3a,field3b,field3c';
$arr[4] = 'field4';
$arr[5] = 'field5';

2 个答案:

答案 0 :(得分:2)

$str = 'field0,field1,field2,"field3a,field3b,field3c",field4,"field5"';
$result = str_getcsv($str, ",", "\"");
print_r($result);

打印:

Array
(
    [0] => field0
    [1] => field1
    [2] => field2
    [3] => field3a,field3b,field3c
    [4] => field4
    [5] => field5
)

答案 1 :(得分:1)

使用Mario的建议:str_getcsv($str, ',', '"');