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.
Original Answer
You can use
str_getcsv()for this as it is purposely designed for process CSV strings:$outis 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:Update for comments
If the quotes are important to you then you can just add them back in like so:
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.