Search code examples
phpregexquotesdouble-quotes

How to remove commas between double quotes in PHP


Hopefully, this is an easy one. I have an array with lines that contain output from a CSV file. What I need to do is simply remove any commas that appear between double-quotes.

I'm stumbling through regular expressions and having trouble. Here's my sad-looking 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

?>

Thanks VERY much, everyone.


Solution

  • Original Answer

    You can use str_getcsv() for this as it is purposely designed for process CSV strings:

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

    $out is now an array of elements without any commas in them, which you can then just implode as the quotes will no longer be required once the commas are removed:

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

    Update for comments

    If the quotes are important to you then you can just add them back in like so:

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

    Another option is to use one of the str_putcsv() (not a standard PHP function) implementations floating about out there on the web such as this one.