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

标签 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] =>
)

我希望将姓名和电子邮件放在一起而不是分开。我错过了什么?

最佳答案

$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>",
^                                    ^ ^                                ^

关于php - 如何使用 str_getcsv() 并忽略引号之间的逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566376/

相关文章:

php - 如何在 CodeIgniter 中将 HTML、PHP 内容插入数据库

PHPMailer发送没有表单数据的邮件

php - 在 Eloquent 关系中使用 withTrashed

Javascript 正则表达式在特定单词或数字后分割

r - 使用正则表达式有选择地提取 R 中的子字符串

c - regexec 损坏 const char * 参数

powershell - 如何在Powershell中CVS的任何一个字段为null时删除整个行?

php - 从多到多将多行分组为一行

r - 按组写入多个csv文件

python - 如何在没有 next() 的情况下读取文件 csv?