preg_replace get number regardless

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

preg_replace get number regardless

Post by hawleyjr »

I have a field in which the user enters in a $ amount. However, if the user enters in $100 or $40.01 or $1,300.00 Instead of throwing an error I would like the value without the $ sign or comma. I know I can do this with str_replace() however, if the user enters "100 dollars" I would still like to process the 100. I know this will involve using reg_replace and that is why I 'm asking for help.

Thanks.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

preg_replace('#ї^\d\.]#','',$text);
beware of things like 10.1.1.53 though.. that'd pass untouched.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Thanks Feyd,

Out of curiosity is there a benefit to doing the reg_replace vs settype?

http://us4.php.net/manual/en/function.settype.php

Code: Select all

#http://us4.php.net/manual/en/function.settype.php
$foo = "5bar"; // string
settype($foo, "integer"); // $foo is now 5  (integer)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

if any character other than a number appears in front, it'll always set to zero.
Post Reply