626
626

Reputation: 1159

PHP Parse Comma Separated String with double quotes

I have a url parameter named data that contains a comma separated string with some enclosed in double quotes like this:

localhost/index.php?data=val1,val2,val3,"val4","val5",val6

I am trying to parse the string and put it into an array. Using str_getcsv($_GET['data'],',','"'); gives me the output like this:

Array
(
    [0] => val1
    [1] => val2
    [2] => val3
    [3] => 
)

I would like the array to look like this:

    Array
(
    [0] => val1
    [1] => val2
    [2] => val3
    [3] => val4
    [4] => val5
    [5] => val6
)

Thanks in advance!

Upvotes: 0

Views: 1022

Answers (2)

user5051310
user5051310

Reputation:

Have you tried using explode? It'll separate a string into an array using whatever separator you specify.

Using your example,

$_GET['data'] = 'val1,val2,val3,"val4","val5",val6';
$testarr = explode(",", $_GET['data']);

var_dump($testarr);

Outputs:

array(6) {
  [0]=>
  string(4) "val1"
  [1]=>
  string(4) "val2"
  [2]=>
  string(4) "val3"
  [3]=>
  string(6) ""val4""
  [4]=>
  string(6) ""val5""
  [5]=>
  string(4) "val6"
}

Looking at your question again, it seems you might want to remove the " from $_GET['data'] entirely?. If so, do this:

$testarr = explode(",", str_replace('"','',$_GET['data']));

Upvotes: 0

developerwjk
developerwjk

Reputation: 8659

I would say urlencode the double quotes when generating that url. Because <a href="localhost/index.php?data=val1,val2,val3,"val4","val5",val6">link</a> will result in the url you go to only being localhost/index.php?data=val1,val2,val3,

So like:

echo '<a href="localhost/index.php?data=' . urlencode('val1,val2,val3,"val4","val5",val6') . '">link</a>';

Upvotes: 1

Related Questions