2

I have a string with this value:

$myValue = "1.099,90";

And I want to replace commas with dots and vice versa. Just like this:

$myNewValue = "1,099.90";

I know that there must be other better ways of doing this, but all I can get is:

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

This way looks weird and has a bad smell! Is there a cleaner way?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136

2 Answers2

4

strtr() doesn't replace replacements, so you can avoid the temporary piping.

Code: (Demo)

$myValue = "7.891.099,90";
echo strtr($myValue, ".,", ",.");

// or
// echo strtr($myValue, ["." => ",", "," => "."]);

Output:

7,891,099.90

Resource: http://php.net/manual/en/function.strtr.php

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
1

This will get the job done, but you could definitely use preg_replace to come up with a different method as well.

<?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;

You can also use the str_replace w/ extra | symbol (or anything)...

<?php
$myValue = '1.099,90';
$replace = array(",", ".", "|");
$with = array("|", ",", ".");
$myNewValue = str_replace($replace, $with, $myValue);
echo $myNewValue;
?>
Nerdi.org
  • 895
  • 6
  • 13