Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Currency Regular Expression

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

like image 302
Lee Avatar asked Dec 18 '22 08:12

Lee


2 Answers

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.

like image 68
The Pixel Developer Avatar answered Dec 27 '22 11:12

The Pixel Developer


How about this

if (preg_match('/^\d+(\.\d{2})?$/', $subject))
{
   // correct currency format
} else {
  //invalid currency format
}
like image 40
Starx Avatar answered Dec 27 '22 11:12

Starx