user629300
user629300

Reputation: 47

Remove all commas if inside pairs of double quotes

I have a string like: "x", "x,y" , "x,y,h".

I want to remove only the commas inside of double quotations and return the string as:

"x", "xy" , "xyh"

Upvotes: 0

Views: 156

Answers (5)

mickmackusa
mickmackusa

Reputation: 48081

Without going down the path of a convoluted regex with the \G (continue) metacharacter, you can match and sanitize substrings which start and and with a double quote.

Code: (Demo)

$text = '"x", "x,y" , "x,y,h"';
echo preg_replace_callback('/"[^"]+"/', fn($m) => str_replace(',', '', $m[0]), $text);
// "x", "xy" , "xyh"

The above doesn't accommodate the possibility of escaped double quotes in the string.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

I use the following, which I've found is generally faster than regexp for this type of replacement

$string = '"x", "x,y" , "x,y,h"';
$temp = explode('"',$string);
$i = true;
foreach($temp as &$value) {
    //  Only replace in alternating array entries, because these are the entries inside the quotes
    if ($i = !$i) {
        $value = str_replace(',', '', $value);
    }
}
unset($value);
//  Then rebuild the original string
$string = implode('"',$temp);

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43265

This would work fine: http://codepad.org/lq7I5wkd

<?php
$myStr = '"x", "x,y" , "x,y,h"';
$chunks = preg_split("/\"[\s]*[,][\s]*\"/", $myStr);
for($i=0;$i<count($chunks);$i++)
   $chunks[$i] = str_replace(",","",$chunks[$i]);
echo implode('","',$chunks);

?>

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 132071

You dont need preg_replace() here and whereever possible you should trying to avoid it

$string = str_replace(',', '', $string);

Upvotes: 1

user585756
user585756

Reputation:

You can just use a regular replace.

$mystring = str_replace(",", "", $mystring);

Upvotes: 1

Related Questions