Can you help me to convert the below string using php?
$str = '1,2,"$1,613","1,740","1,740"'
=>
$str = '1,2,$1613,1740,1740'
CodePudding user response:
You can use a RegEx to remove quotes and commas inside them:
$str = '1,2,"$1,613","1,740","1,740"';
$result = preg_replace('~"(\$?\d ),(\d )"~', '$1$2', $str);
Value:
1,2,$1613,1740,1740
The 1st group captures the optional dollar sign and the first digits, the 2nd group captures the last digits.
But in case you have values like 1,234,567 this would not work. I'd use a modified version of this answer to remove commas between quotes, or quotes:
$str = '1,2,"$1,613","1,154,740","1,740"';
$result = preg_replace('~(,(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)|")~', '', $str);
Value:
1,2,$1613,1154740,1740
The left side of the group gets the commas between quotes, the right side just gets the quotes.
