Reputation: 47
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
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
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
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
Reputation: 132071
You dont need preg_replace()
here and whereever possible you should trying to avoid it
$string = str_replace(',', '', $string);
Upvotes: 1
Reputation:
You can just use a regular replace.
$mystring = str_replace(",", "", $mystring);
Upvotes: 1