View Full Version : Resolved PHP Math Help(Decimal Places)

01-07-2010, 06:18 PM
Okay I want to allow users to input numbers, I am currently using this to make sure there are no spaces or letters:

$A= preg_replace("/[^0-9]/","",$A);

I want to allow users to input decimal places. I tried using this:

$A= preg_replace("/[^0-9]+\.[0-9]/","",$A);

But it seems to be allowing letters through again.

01-07-2010, 07:02 PM
this seems to work:


01-07-2010, 07:31 PM

@angst - yours will work, but it will allow all sorts, such as

01-07-2010, 07:39 PM
@Jay - I've tried to use what you've shown in your example, but it returns an null value every time.

$A= preg_replace("/^\d+(\.\d+)?$/","",$A);

01-07-2010, 07:42 PM
Oh I see, sorry I thought you were trying to match the string as a valid number
Use this

$A= preg_replace("/^.*?(\d+(\.\d+)?).*$/","$1",$A);That should do it

01-07-2010, 07:44 PM
I've gotten it working somewhat as:

$B= preg_replace("/[^\d+](\.\d+)?$/","",$B);

But my main problem is if I put letters before the numbers it doesn't take the letters out, for example I input 3.w3 I get 3.

01-07-2010, 07:56 PM
can you give an example of the input string

01-07-2010, 08:14 PM
3.w2 would be an input( a bad one that I'm trying to filter out), it should appear as 3.2, but the "w" sticks and PHP will treat it as a 3.

01-07-2010, 09:03 PM
oh I see. this should work. Note that I had to use two regexes just in case there are any periods either side of the number after the letters are removed

$a = '..asdf.sdf.wfef.3.wsdf2.fewf.wef';
$a = preg_replace('/[^\d\.]+/', '', $a);
$a= preg_replace("/^.*?(\d+(\.\d+)?).*$/","$1", $a);
echo $a;