PHP Currency Regular Expression
Question
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
Solution
if (preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $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.
OTHER TIPS
How about this
if (preg_match('/^\d+(\.\d{2})?$/', $subject))
{
// correct currency format
} else {
//invalid currency format
}
You might want to consider other alternatives to using a regex.
For example, there's the NumberFormatter
class, which provides flexible number and currency parsing and formatting, with build in internationalisation support.
It's built into PHP 5.3 and later, and is available as an extension on earlier versions of PHP 5.
Try this regular expression:
^(?:[1-9]\d+|\d)(?:\.\d\d)?$