regular expression
I'm a php'er that needs to match any positive number with up to 2 decimal places using ereg. I see lots of regex examples for floating points, but none that limit the number of decimal places. Can anyone help by providing an example for this specific match?
|
Hi,
I need more info. Do you want to find only numbers with 2 or less decimals and not ones with more? or, do you want to find all numbers and the ones with more than 2 decimals, chop off the extra numbers. |
Not sure how usefull my reply will be since i don't know PHP, but what you might want to try (if PHP has dynamic variable typing like Perl) is to test the value as a string and then check for the period follow by certain number of digits:
Something along these lines: /^[^-][\d]+(.[\d]{1,2})?$/ [^-] => no minus signs [\d]+ => match one or more digits (.[\d]{1, 2})? => either nothing or a period followed by upto 2 digits. |
here is a PHP program that should do what you want.
just copy it to a file and run it at the command line let know if you need more help michael #!/usr/bin/php <?php $varSet = array("1", "2.0", "3.1", "4.21", "5.321", "6.4321", "7.54", "-8.65", "-9.765"); for ($n = 0; $n < 9; $n++) { if (ereg("^[^-]+((\.)([[:digit:]]{0,2}))$", $varSet[$n])) { printf("%s\n", $varSet[$n]); } } ?> |
All times are GMT -5. The time now is 03:46 PM. |