CSV handling functions (fgetcsv()
, fputcsv()
) are much better for this - they will handle edge cases and will likely be far more reliable than any regex you can come up with.
// 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);
EDIT Following your comment about not wanting to read from/write to disk, you can do this:
// 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);