phpcsvexplode

Split a string on commas unless comma is inside single quotes


I have a problem, I want to split a string variable using the explode function but there are a limitation, imagine having the next string variable with the next value :

$data = "3, 18, 'My name is john, i like to play piano'";

Using the explode function : explode(",", $data), the output will be :

array(
    [0] => 3,
    [1] => 18,
    [2] => 'My name is john,
    [3] => i like to play piano'
);

My target is to split the variable $data by comma excluding the ones that are between ' ' chatacters.

Desired result:

array(
    [0] => 3,
    [1] => 18,
    [2] => 'My name is john, i like to play piano'
);

Solution

  • This looks rather like CSV data. You can use str_getcsv to parse this.

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

    should result in:

    array(3) {
      [0] =>
      string(1) "3"
      [1] =>
      string(3) " 18"
      [2] =>
      string(12) "My name is john, i like to play piano"
    }
    

    You may want to apply trim to each of the array elements too, by using array_map:

    $string = "3, 18, 'My name is john, i like to play piano'";
    var_dump(array_map('trim', str_getcsv($string, ',', "'")));