Phil
Phil

Reputation: 14681

Parse a single-line csv string containing double-quoted values

I have a string like:

$string = '"lorem ipsum","dolor, sit","amet"';

I am trying to use EXPLODE and preg_match in order to get each of the elements within " .. " as a string on its own, rendering the original string into an array.

Which would give me in the end;

$array[0] = 'lorem ipsum';
$array[1] = 'dolor, sit';
$array[2] = 'amet';

Some strings-to-be contain comma inbetween so my attempts of trying explode to separate them and then replacing or preg_matching to extract in between " .. " fails.

How can I achieve the desired goal?

Thank you.

Upvotes: 1

Views: 61

Answers (3)

lanzz
lanzz

Reputation: 43208

This code should iteratively parse your string into its components:

$array = array();
while (preg_match('/^"([^"]*)"(?:,(.*)|$)/', $string, $match)) {
    $array[] = $match[1];
    $string = @$match[2];
}

Upvotes: 1

jeroen
jeroen

Reputation: 91792

You should replace your combination of functions with a function that is made specifically for this: str_getcsv:

$array = str_getcsv($string, ',', '"');

(options added for clarity)

Upvotes: 1

PenguinCoder
PenguinCoder

Reputation: 4367

What you are looking for is preg_split:

$string = preg_split("/,[^\s+]/", '"lorem ipsum","dolor, sit","amet"');
print_r($string);

>

Array
(
    [0] => "lorem ipsum"
    [1] => dolor, sit"
    [2] => amet"
)

Upvotes: 0

Related Questions