Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use str_getcsv() and ignore commas between quotes?

Tags:

regex

php

csv

Here's my current code.

<?php$da_data = $_POST['dadata'];
$da_data = htmlspecialchars($da_data, ENT_QUOTES);
$da_data = str_replace('&lt;', '', $da_data);
$da_data = str_replace("&gt;", '', $da_data);
$da_data = str_getcsv($da_data,  ",", "'");
print_r($da_data);
?>

Example data:

"Bill, Rose Mary" <[email protected]>,"asasd, test" <[email protected]>,

it's spitting out

Array (
[0] => \"Bill
[1] => Rose Mary\" [email protected]
[2] => \"asasd
[3] => test\" [email protected]
[4] =>
)

I'd like to have the name and email together opposed to separated. What am I missing?

like image 670
Kenny Avatar asked Mar 21 '14 18:03

Kenny


1 Answers

$da_data = str_getcsv($da_data,  ",", "'");
//                                     ^

would read this like you want:

'Bill, Rose Mary' <[email protected]>,'asasd, test' <[email protected]>,
^               ^                      ^           ^

But you don't use single quotes in your CSV file like you specified in your str_getcsv call. It's ":

$da_data = str_getcsv($da_data,  ',', '"');
//                                     ^

var_dump($da_data);

Output:

array(3) {
  [0]=>
  string(36) "Bill, Rose Mary <[email protected]>"
  [1]=>
  string(32) "asasd, test <[email protected]>"
  [2]=>
  string(0) ""
}

DEMO

Please do note that it removes your " as they're actually supposed to be enclosing the entire string.

On a completely different note, to make sure that you get the right data you should transform your CSV file into the following:

"Bill, Rose Mary <[email protected]>","asasd, test <[email protected]>",
^                                    ^ ^                                ^
like image 57
h2ooooooo Avatar answered Oct 28 '22 08:10

h2ooooooo