PHP Currency Regular Expression
Question by Lee
I am trying to find a piece of regex to match a currency value.
I would like to match only numbers and 1 decimal point ie
Allowed
- 10
- 100
- 100.00
Not Allowed
- Alpha Characters
- 100,00
- +/- 100
I have search and tried quite a few without any luck.
Hope you can advise
Answer by The Pixel Developer
if (preg_match('/^[0-9]+(?:.[0-9]+)?$/im', $subject))
{
# Successful match
}
else
{
# Match attempt failed
}
Side note : If you want to restrict how many decimal places you want, you can do something like this :
/^[0-9]+(?:.[0-9]{1,3})?$/im
So
100.000
will match, whereas
100.0001
wont.
If you need any further help, post a comment.
PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.
Answer by Starx
How about this
if (preg_match('/^d+(.d{2})?$/', $subject))
{
// correct currency format
} else {
//invalid currency format
}