如何用点替换逗号,反之亦然

时间:2018-10-12 03:04:14

标签: php replace currency-formatting digit-separator

我有一个具有以下值的字符串:

$myValue = "1.099,90";

我想用点代替逗号,反之亦然。就是这样:

$myNewValue = "1,099.90";

我知道这样做必须是其他更好的方法。但是我能得到的是:

$myNewValue = str_replace(",","|",$myValue);
$myNewValue = str_replace(".",",",$myValue);
$myNewValue = str_replace("|",".",$myValue);

但是这种方式看起来很奇怪和难闻的气味! 有什么好主意吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

strtr()不会替代替换品,因此可以避免临时配管。

代码:(Demo

$myValue = "1.099,90";
echo strtr($myValue, ["." => ",", "," => "."]);

输出:

1,099.90

资源:http://php.net/manual/en/function.strtr.php

答案 1 :(得分:1)

这可以完成工作,但是您当然也可以使用preg_replace提出另一种方法。

<?php
$myValue = '1.099,90';
$parts = explode(".", $myValue); // break up the (.)periods
$num = count($parts); // number of parts
for($loop = 0; $loop < $num; $loop++){ // cycle through each part
    if(strpos($parts[$loop], ",") !== false){ // if this includes (,)comma - swap it
        $parts[$loop] = str_replace(",", ".", $parts[$loop]);
    }
    if($loop !== ($num - 1)){ // if this is not the last loop iteration..add comma after (replace period)
        $myNewValue .= $parts[$loop] . ","; 
    } else {
        $myNewValue .= $parts[$loop]; // last loop iteration, no comma at end
    }
}

echo $myNewValue;

您还可以使用带有多余|的str_replace |。符号(或其他任何东西)...

<?php
$myValue = '1.099,90';
$replace = array(",", ".", "|");
$with = array("|", ",", ".");
$myNewValue = str_replace($replace, $with, $myValue);
echo $myNewValue;
?>