Mihir
Mihir

Reputation: 1176

Split string on commas not inside double quotes

I want to split following string with a comma.

1,"x1",43,"tr","y,7"

Result array should be like following.

[
    0 => '1',
    1 => '"x1"',
    2 => '43',
    3 => '"tr"',
    4 => '"y,7"'
]

In short, it should not consider comma if it is between quotes.

If I use explode, I will get following result, which I don't want.

[
    0 => '1',
    1 => '"x1"',
    2 => '43',
    3 => '"tr"',
    4 => '"y',
    5 => '7"'
]

I am stuck here, please help.

Upvotes: 0

Views: 282

Answers (3)

Curlas
Curlas

Reputation: 899

Easy!! Your string is a CSV.

Use $your_array=str_getcsv($your_string);

Upvotes: 1

miku
miku

Reputation: 188234

Try str_getcsv:

<?php

$s = '1,"x1",43,"tr","y,7"';
$result = str_getcsv($s);
var_dump($result);
echo "\n";

// array(5) {
//   [0]=>
//   string(1) "1"
//   [1]=>
//   string(2) "x1"
//   [2]=>
//   string(2) "43"
//   [3]=>
//   string(2) "tr"
//   [4]=>
//   string(3) "y,7"
// }


?>

Upvotes: 3

Bart Kiers
Bart Kiers

Reputation: 170308

The following snippet:

$s = '1,"x1",43,"tr","y,7"';
print_r(preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $s));

produces:

Array
(
    [0] => 1
    [1] => "x1"
    [2] => 43
    [3] => "tr"
    [4] => "y,7"
)

as can be seen on ideone.

The regex ,(?=([^"]*"[^"]*")*[^"]*$) means: match a comma, only if it has zero, or an even number of double quotes ahead of it.

Upvotes: 2

Related Questions