我有一个CSV文件,我们知道的Excel用双引号括起来,例如做它的事,在现场逗号我有一个文件CSV删除逗号在引号用正则表达式
Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB
哪有我使用RegExp将引号替换为“。”。代替但是仅限于引号,所以我得到
Product Name,Product Code
Product 1,AAA
Prod.A.B,BBB
作为输出
我有一个CSV文件,我们知道的Excel用双引号括起来,例如做它的事,在现场逗号我有一个文件CSV删除逗号在引号用正则表达式
Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB
哪有我使用RegExp将引号替换为“。”。代替但是仅限于引号,所以我得到
Product Name,Product Code
Product 1,AAA
Prod.A.B,BBB
作为输出
CSV处理功能(fgetcsv()
,fputcsv()
)是多少为了这个美好的 - 他们会处理边缘情形和可能会比任何正则表达式,你可以拿出更为可靠。
// Open the file
$fp = fopen($pathToCsvFile, 'r+');
// Create an array of modified data
$tmp = array();
while (($row = fgetcsv($fp, 8192)) !== FALSE) {
foreach ($row as &$field) $field = str_replace(',', '.', $field);
$tmp[] = $row;
}
// Truncate the file and put the pointer at the beginning
ftruncate($fp, 0);
rewind($fp);
// Write the modified data back and close the file
foreach ($tmp as $row) {
fputcsv($fp, $row);
}
fclose($fp);
编辑追随你左右不想读取/写入到磁盘评论,你可以这样做:
// Lets say the raw CSV data is held in this variable as a string
$rawCsvData = 'Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB';
// Open a virtual file pointer to memory and fill it with your data
$fp = fopen('php://memory', 'w+');
fwrite($fp, $rawCsvData);
// Start from the beginning of the pointer
rewind($fp);
// ... INSERT CODE FROM ABOVE HERE (minus the fopen()/fclose())
$modifiedCsvData = stream_get_contents($fp);
fclose($fp);
这将做多的内容替换,并删除引号。
<?php
$data = 'Product Name,Product Code
Product 1,AAA
"Prod,A,B",BBB';
$rgx = '/"(.+?)"/';
preg_match_all($rgx, $data, $matches);
$x = 0; $max = count($matches[0]);
while($x < $max){
$replace = str_replace(",", ".", $matches[1][$x]);
$data = str_replace($matches[0][$x], $replace, $data);
$x++;
}
echo $data;
?>
工程很棒!对于其他人,请确保您的文件具有正确的编码,如果此页面上没有任何内容可以运行 – Akshat 2012-01-27 14:43:32
@Akshat很好用 - 直到该值还包含双引号。然后它会中断,因为正则表达式不考虑转义。这就是为什么CSV处理函数是这样做的原因 - 你所做的任何事情都不会像他们那样处理边缘案例。 – DaveRandom 2012-01-27 14:48:15
为什么你需要做到这一点? PHP的CSV处理函数可以使用可选的引用字段。 – 2012-01-27 14:12:19
阅读关于此 - > http://php.net/manual/en/function.preg-replace.php – Tudor 2012-01-27 14:12:51
我直接从数据库中读取我的csv转换为文本blob字段,我不想将它写入光盘 – Akshat 2012-01-27 14:20:54