...

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



kochier
01-07-2010, 07: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.

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



preg_replace("/[^0-9.]/","",$string);

JAY6390
01-07-2010, 08:31 PM
Use
'/^\d+(\.\d+)?$/'

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

kochier
01-07-2010, 08: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);

JAY6390
01-07-2010, 08: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

kochier
01-07-2010, 08: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.

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

kochier
01-07-2010, 09: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.

JAY6390
01-07-2010, 10: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;



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum