如何仅在引用的子字符串中用点替换逗号?

时间:2018-09-05 09:58:43

标签: php regex string codeigniter

假设我有一个字符串:

$string =  'apple, cat, dog, "0,445",symphony, "0,454"';

我想要的输出是:

$string =  'apple, cat, dog, "0.445",symphony, "0.454"';

3 个答案:

答案 0 :(得分:5)

您可以使用preg_replace

$string = preg_replace('/("\d+),(\d+")/','$1.$2',$string);

答案 1 :(得分:1)

请根据您的要求找到解决方法,

$string = 'apple, cat, dog, "0.445",symphony, "0,454"';
$array = str_replace('*comma*', ',', explode(',',preg_replace_callback('|"[^"]+"|', function ($matches) {return str_replace(',', '*comma*', $matches[0]);}, $string)));
foreach ($array as $key => $value) {
    $array[$key] = str_replace(',', '.', $value);
}
$string = implode(",", $array);

我引用了link。这是您的工作code

答案 2 :(得分:1)

尝试使用此正则表达式:https://regexr.com/3uvj0

$string = preg_replace('/(\".)(,)(.*\")/', '$1.$3', $string);