Nathan Nathan - 1 year ago 82
PHP Question

PHP: Validate a given string is a valid number

I am trying to write a function that validates whether or not a given string is a valid number. I know I can use PHP is_numeric(), but the requirements is that the function needs to recognize commas as valid when:

  • Commas are in the whole number part of the number

  • Each comma has 3 whole number digits following it

  • At least one digit left of each comma

  • No more than 3 contiguous digits to the left of a comma

For instance:
It should recognize: 1,000,230 not ,021,201 or 1,023,12
It should also recognize positive and negative and dollar sign in front of it.

I am thinking to use preg_match to check the number format but I am not familiar with preg_match. Can you help me with this ? Any tip is appreciated ! Thank you !

Answer Source

You could use this function:

function hasNumericFormat($str) {
    return preg_match("/^[-+]?[$]?([1-9]\d{0,2}(,\d{3})*|0)(\.\d+)?$/", $str);

Test code:

function test($str) {
    if (hasNumericFormat($str)) {
        echo "$str is OK<br>";
    } else {
        echo "$str violates numerical format<br>";

test("-$1,234,567.89"); // ok
test(",123,567.89"); // not ok: digit missing before comma
test("1,123,56"); // not ok: not 3 digits in last group
test("-0,123,567"); // not ok: first digit is zero
test("+0"); // ok

See it run on

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download