Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
Sfah Bbbzfhiuj Avatar asked Dec 21 '22 21:12

Sfah Bbbzfhiuj


2 Answers

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.

like image 77
Treffynnon Avatar answered Dec 29 '22 12:12

Treffynnon


This is a very naive approach that will work only if 'valid' commas are those that are between quotes with nothing else but maybe whitespace between.

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

It should def be tested more but it works in this case.

Cases where it might not work is where you don't have quotes in the string.

one,two,three,four -> onetwothreefour

EDIT : Corrected the issues with deleting spaces and neighboring letters.

like image 36
Jerry Saravia Avatar answered Dec 29 '22 13:12

Jerry Saravia