Kelle
Kelle

Reputation: 15

PHP - filter_var REGEXP won't find Zero

I'm wondering why I can't match the number zero => 0 with PHPs filter_var function and with PHPs preg_match it can find the number zero.

Can anybody help me how I got this to work with filter_var or is this a bug ?

Code snippet:

if(!filter_var("0", FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[0-9]+$/i')))) {
        print_r("NO MATCH!");
    } else {
        print_r("MATCH!");
    }

Result: NO MATCH!

Code snippet:

if(preg_match('/^[0-9]+$/i', "0") == 0) {
    print_r("NO MATCH!");
} else {
    print_r("MATCH!");
}

Result: MATCH!

Upvotes: 0

Views: 347

Answers (1)

hakre
hakre

Reputation: 198117

The PHP function filter_var() returns the filtered result. From the PHP manual:

Return Values

Returns the filtered data, or FALSE if the filter fails.

You practically did the same mistake as the user asking in filter_var using FILTER_VALIDATE_REGEXP: The function does not validate input, it filters it. In case it does not match, it will return FALSE otherwise it will return the filtered data. And that is the string "0" which evaluates to false in PHP if you cast it to boolean which happens by using the negation operator (!).

Therefore you checked:

if (!"0") {
    print_r("NO MATCH!");
} else {
    print_r("MATCH!");
}

Which is what it is. So you output about "match" but you "if" about the value itself, not the match operation.

Write better code by just making use a simple variable assignment:

$var    = "0";
$result = filter_var($var, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[0-9]+$/i')));

if (!$result) {
    print_r("NO MATCH!");
} else {
    print_r("MATCH!");
}

This will then allow you to trouble-shoot and change more easily:

var_dump($result); // string(1) "0"

And further:

$var    = "0";
$result = filter_var($var, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => '/^[0-9]+$/i')));

if ($var !== $result) {
    print_r("NO MATCH!");
} else {
    print_r("MATCH!");
}

Is what you perhaps wanted to write earlier. Output:

MATCH!

Upvotes: 1

Related Questions