How to remove commas between double quotes in PHP

Hope this is easy. I have an array with strings that contain the output from a CSV file. I just need to remove any commas that appear between double quotes.

I stumble over regular expressions and have problems. Here is my sad code:

<?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

?>

Thank you very much, everyone.

+3
source share
3 answers

Original answer

You can use str_getcsv()this because it is specifically designed for CSV process lines:

$out = array();
$array = str_getcsv($csv_input);
foreach($array as $item) {
    $out[] = str_replace(',', '', $item);
}

$out now it is an array of elements without any commas in them, which you can simply explode, since the quotation marks will no longer be needed after removing the commas:

$revised_input = implode(',', $out);

Comment update

, :

$revised_input = '"' . implode('","', $out) . '"';

str_putcsv() ( PHP) , , .

+5

, , "" - , , , , .

<?php    

$csv_input = '"herp","derp","hey, get rid of these commas, man",1234';

$pattern = '/([^"])\,([^"])/'; //this doesn't work

$revised_input = preg_replace ( $pattern , "$1$2" , $csv_input);

echo $revised_input;

//ouput for this is: "herp","derp","hey get rid of these commas man",1234

, .

, , - , .

, , , → onetwothreefour

EDIT: .

+1

.

, (, , ), , -, ?

Once you find an open quote, you can check the rest of the line; anything before the next quote is part of this element. You can add some checks here to look for escaped quotes, so things like:

"this is a \"quote\""

will still be read correctly.

0
source

All Articles