PHP explode()函数的使用

PHP explode()函数的使用,php,explode,Php,Explode,我有一个问题,我想使用explode函数拆分一个字符串变量,但有一个限制,想象一下,下一个字符串变量具有下一个值: $data = "3, 18, 'My name is john, i like to play piano'"; 使用explode函数:explode(“,”,$data),输出将是: array( [0] => 3, [1] => 18, [2] => 'My name is john, [3] =&

我有一个问题,我想使用explode函数拆分一个字符串变量,但有一个限制,想象一下,下一个字符串变量具有下一个值:

$data = "3, 18, 'My name is john, i like to play piano'";
使用explode函数:explode(“,”,$data),输出将是:

array(
       [0] => 3,
       [1] => 18,
       [2] => 'My name is john,
       [3] => i like to play piano'
      );
我的目标是用逗号分割变量$data,不包括位于“”chatacter之间的变量

e、 g.
数组(
[0] => 3,
[1] => 18,
[2] =>“我叫约翰,我喜欢弹钢琴”
);


如果有人能告诉我这样做的方法,我将不胜感激。

这看起来很像CSV数据。您可以使用来解析这个

var_dump(str_getcsv("3, 18, 'My name is john, i like to play piano'", ',', "'"));
应导致:

array(3) {
  [0] =>
  string(1) "3"
  [1] =>
  string(3) " 18"
  [2] =>
  string(12) "My name is john, i like to play piano"
}
您也可以使用
array\u map
trim
应用于每个数组元素:

$string = "3, 18, 'My name is john, i like to play piano'";
var_dump(array_map('trim', str_getcsv($string, ',', "'")));
您可以将该功能用作:

$data = "3, 18, 'My name is john, i like to play piano'";
$pieces = str_getcsv($data, ',', "'");
函数的第一个参数是要拆分的字符串

第二个参数是需要拆分的分隔符

第三个参数是单个字符,当在第一个参数中用作一对(未转换)时,将被视为一个字段,有效地忽略这对参数之间的分隔符。

使用:

// set the delimiter with ',', and set enclosure with single quote
$arr = str_getcsv ($data, ',', "'");

如果您的数据总是具有相同的结构:explode(“,”,$data,3);else str_getcsv()