2012-01-27 133 views
1

我有一個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 

作爲輸出

+1

爲什麼你需要做到這一點? PHP的CSV處理函數可以使用可選的引用字段。 – 2012-01-27 14:12:19

+0

閱讀關於此 - > http://php.net/manual/en/function.preg-replace.php – Tudor 2012-01-27 14:12:51

+0

我直接從數據庫中讀取我的csv轉換爲文本blob字段,我不想將它寫入光盤 – Akshat 2012-01-27 14:20:54

回答

5

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

這將做多的內容替換,並刪除引號。

<?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; 
?> 
+0

工程很棒!對於其他人,請確保您的文件具有正確的編碼,如果此頁面上沒有任何內容可以運行 – Akshat 2012-01-27 14:43:32

+0

@Akshat很好用 - 直到該值還包含雙引號。然後它會中斷,因爲正則表達式不考慮轉義。這就是爲什麼CSV處理函數是這樣做的原因 - 你所做的任何事情都不會像他們那樣處理邊緣案例。 – DaveRandom 2012-01-27 14:48:15