希望这是一个简单的过程。我有一个包含 CSV 文件输出的行的数组。我需要做的只是删除出现在双引号之间的所有逗号。
我在正则表达式中结结巴巴,遇到了麻烦。这是我看起来很悲伤的代码:
<?php
$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';
$pattern = '(?<=\")/\,/(?=\")'; //this doesn't work
$revised_input = preg_replace ( $pattern , '' , $csv_input);
echo $revised_input;
//would like revised input to echo: "herp","derp,"hey get rid of these commas man",1234
?>
非常感谢大家。
最佳答案
原始答案
您可以使用 str_getcsv()
为此,因为它是专门为处理 CSV 字符串而设计的:
$out = array();
$array = str_getcsv($csv_input);
foreach($array as $item) {
$out[] = str_replace(',', '', $item);
}
$out
现在是一个没有任何逗号的元素数组,您可以将其内爆,因为删除逗号后将不再需要引号:
$revised_input = implode(',', $out);
评论更新
如果引用对您很重要,那么您可以像这样将它们添加回去:
$revised_input = '"' . implode('","', $out) . '"';
另一种选择是使用网上流传的 str_putcsv()
(不是标准的 PHP 函数)实现,例如 this one .
关于php - 如何在 PHP 中删除双引号之间的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739016/