如何使用str_getcsv()并在引号之间忽略逗号?

时间:2014-03-21 18:08:11

标签: php regex csv

这是我目前的代码。

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

示例数据:

"Bill, Rose Mary" <bill@co.bill.ca.us>,"asasd, test" <test@co.test.ca.us>,

它随地吐痰

Array (
[0] => \"Bill
[1] => Rose Mary\" bill@co.bill.ca.us
[2] => \"asasd
[3] => test\" test@co.test.ca.us
[4] =>
)

我希望将名称和电子邮件放在一起反对分开。我错过了什么?

1 个答案:

答案 0 :(得分:4)

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

会像你想要的那样阅读:

'Bill, Rose Mary' <bill@co.bill.ca.us>,'asasd, test' <test@co.test.ca.us>,
^               ^                      ^           ^

但您不能像在str_getcsv电话中指定的那样在CSV文件中使用单引号。它是"

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

var_dump($da_data);

输出:

array(3) {
  [0]=>
  string(36) "Bill, Rose Mary <bill@co.bill.ca.us>"
  [1]=>
  string(32) "asasd, test <test@co.test.ca.us>"
  [2]=>
  string(0) ""
}

DEMO

请注意,它会移除",因为他们实际上应该包含整个字符串。

完全不同的说明,为了确保您获得正确的数据,您应该将CSV文件转换为以下内容:

"Bill, Rose Mary <bill@co.bill.ca.us>","asasd, test <test@co.test.ca.us>",
^                                    ^ ^                                ^
相关问题