PDA

View Full Version : Help with preg_replace?


kaisellgren
09-05-2006, 02:03 PM
Hi,

Can you help me how to change a 1.0.0 to 1.00, and how to 2.0.0 to 2.0 ... this same code should also change 1.0 to 1.0 and 1.00 to 1.00, so basicly it deletes the second dot, but not the first..

lavinpj1
09-05-2006, 07:28 PM
<?php
$test = 'hello 0.8.7 hello';
echo preg_replace('@([0-9]\.[0-9])\.([0-9])@', '$1$2', $test);
?>

~Phil~

Sayonara
09-05-2006, 07:31 PM
Have you tried cheating by using the money format (http://uk2.php.net/manual/en/function.money-format.php) function?

A bit less server-intensive, I would have thought.

lavinpj1
09-05-2006, 07:36 PM
Have you tried cheating by using the money format function?

A bit less server-intensive, I would have thought.

Money_Format was added in 4.3.0 and is not availiable on Windows systems not supporting strfmon. Preg_Replace was added in php 3.0.9 and works happily on windows. Also, money_format takes a parameter as a float, which hampers its usage for replacing (multiple) instances in strings.

~Phil~

Nicklas
09-05-2006, 07:52 PM
$nr = "2.0.0";
$num = preg_replace('/(\d+\.\d+)(.*)/e', '"\\1" . str_replace(".", "", \\2)', $nr);
echo $nr;

lavinpj1
09-05-2006, 08:41 PM
Get some errors on not using the #.#.# format there Nicklas

kaisellgren
09-05-2006, 08:43 PM
Oukki doukki,

Thanks dudes for the regular expressions. I have always wanted to know how it works, but it is just too hard for me or maybe I could if I spend weeks on it.

See you then and thanks