I want to replace all dots in a string to commas, but only for numbers (in PHP):
Like :
this is. an example. 15.68€
and it should be converted to something like this is. an example. 15,68€
Is there an easy preg_replace
or any other option ?
I want to replace all dots in a string to commas, but only for numbers (in PHP):
Like :
this is. an example. 15.68€
and it should be converted to something like this is. an example. 15,68€
Is there an easy preg_replace
or any other option ?
Try this one
$str = "this is. an example. 15.68€";
function cleaner($matches)
{
return str_replace("." , "," , $matches["nrs"]);
}
$str = preg_replace_callback ("/(?P<nrs>[0-9]+.[0-9]+)/" , "cleaner" , $str);
echo $str;
I have used preg_replace_callback
. The behavior of this function is almost identical to preg_replace()
, except for the fact that instead of replacement parameter, one should specify a callback. Check for more about it here. You can also test the live preview of my solution.