Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string on commas unless comma is inside single quotes

Tags:

php

csv

explode

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'
);
like image 866
avolquez Avatar asked Nov 28 '25 06:11

avolquez


1 Answers

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, ',', "'")));
like image 99
cmbuckley Avatar answered Nov 30 '25 19:11

cmbuckley