phpvalidationfilterfilteringw3c

Advantages of using filter_var() with FILTER_VALIDATE vs preg_match()


To validate input date, both form URL or from a form, which technique do you usually use?

I have been looking at PHP Filters but i have rarely see them on any code.

I have usually seen the use of preg_mach, for example:

$numbers = "/^[0-9]+$/D";

if (preg_match($numbers, $var)){
    echo "is number";
}

Instead of:

if(!filter_var($var, FILTER_VALIDATE_INT))
    echo "is number";
}

Is there any advantage using one or another?


Solution

  • Php introduced the filer_ functionality for a wide range of types of variable validation since php 5.2. It's good practice to use the filter_var || filter_input for your needs.

    Besides the fact that it's safer it will also save you lots of development time cracking your head over regular expressions.