avolquez
avolquez

Reputation: 753

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'
);

Upvotes: 2

Views: 4528

Answers (3)

codaddict
codaddict

Reputation: 455360

You can use the str_getcsv() function as:

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

The first argument to the function is the string to be split.

The second argument is the delimiter on which you need to split.

And the third argument is the single character that when used as a pair (unsescaped) inside the first argument, will be treated as one field, effectively ignoring the delimiters between this pair.

Upvotes: 5

cmbuckley
cmbuckley

Reputation: 42517

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, ',', "'")));

Upvotes: 8

xdazz
xdazz

Reputation: 160923

Use: str_getcsv

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

Upvotes: 6

Related Questions