Search code examples
phpregexpreg-match

why does my regular expression number verification patteren accept dots?


I struggle to understand how i can fix this regular expression patteren.

It verifies normal integer numbers correctly, but when i put a dot in the end of the integer it still verifies as a clean input.

How can i change my patteren /[^0-9]/ so that its only numbers 0-9 that is considered a clean input?

        $verify = 1.;
        $regular_exression_filter_integer = "/[^0-9]/";
        if (!preg_match ($regular_exression_filter_integer, $verify)) { 
            echo "clean input";
        } else {
            echo "bad input";
        }

Clean inputs
$filter_this = 1.; 
$filter_this = 1234;

Bad inputs
$filter_this = 1.1;

As described the input of $filter_this = 1.; should give me "BAD INPUT", but it do not.


Solution

  • You cannot run a regex check on integers of floats, only on strings.

    Also, you can make use of a positive preg_match with a regex that checks for integer value in the input that ends in an optional dot:

    $regular_expression_filter_integer = '/^[0-9]+\.?$/';
    $verify = "1.";
    if (preg_match ($regular_expression_filter_integer, $verify)) { 
        echo "clean input";
    } else {
        echo "bad input";
    }
    

    See demo