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

时间:2022-09-13 07:47:57

Suppose I have a string:

假设我有一个字符串:

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

What output I want is:

我想要的输出是:

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

3 个解决方案

#1


5  

You can do that using preg_replace

你可以使用preg_replace做到这一点

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

#2


1  

Try this regular expression : https://regexr.com/3uvj0

试试这个正则表达式:https://regexr.com/3uvj0

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

#3


1  

Please find work around for your requirement,

请找到适合您要求的工作,

$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);

I took the reference of link. Here is your working code.

我参考了链接。这是你的工作代码。

#1


5  

You can do that using preg_replace

你可以使用preg_replace做到这一点

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

#2


1  

Try this regular expression : https://regexr.com/3uvj0

试试这个正则表达式:https://regexr.com/3uvj0

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

#3


1  

Please find work around for your requirement,

请找到适合您要求的工作,

$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);

I took the reference of link. Here is your working code.

我参考了链接。这是你的工作代码。