views:

30

answers:

3

Looking for a simple way (Function/RegEx) to validate a number with grouped thousands.

Example Numbers:

.00 - 999.00 should validate
1,000.00 should validate
100,000.00 etc... should validate
100,000,000,000,000.00 should validate

Now I've seen the number_format(), but this formats the number not validates.

I wanted to use a RegEx but lost on how to do so.

preg_match(/^[\d]\,?\.[\d]{2}$/, $number);

but this doesn't work.

I've also looked at the money_format() but again this is format and not validation.

+1  A: 

Just off the top of my head:

preg_match('%^[\d,]*\.\d{2}$%', $number);

This will match all of the numbers you mentioned (in fact: every string which starts with a combination of digits and commas and ends on "." and to digits).

Again, this is untested but should work.

Turbotoast
This will allow 1000.00 which should be in this format: 1,000.00
Phill Pafford
Oh, you're right. My fault.
Turbotoast
+1 for the effort
Phill Pafford
+1  A: 
^(?:\d{1,3}(?:,\d{3})*)?\.\d{2}$
LukeH
What does the colon in this pattern do?
BenWells
Thanks, just one question. I know the ? makes the character optional but what does this do to the expression :
Phill Pafford
@Ben, @Phill: Do you mean the `?:` parts? They just mean that the parenthesised group is non-capturing. Using non-capturing groups supposedly gives a (very small) performance improvement when you don't actually need to capture the text. http://www.regular-expressions.info/brackets.html
LukeH
Yep. Thanks for the insight and the RegEx
Phill Pafford
A: 

If you've got a PHP5.3+ you could try the Intl number formatter:

http://uk2.php.net/manual/en/numberformatter.parse.php

Robin
Thanks I am running 5.x but it's not a formatting issue but a validation issue. Thanks for the effort
Phill Pafford