Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FILTER_VALIDATE vs Preg_match. Which one to use?

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? Thanks!

like image 624
Alvaro Avatar asked Jan 16 '23 01:01

Alvaro


2 Answers

My two cents: It depends.

It depends on the situation on whether you should use the filter functions over a regex. Actually, the criteria is pretty simple:

Is there a filter_* function that exists that validates exactly the kind of input I'm expecting?

  • If so, use that filter_* function.
  • Otherwise, use a regex.

Regexs are more complex than the filter_* functions, but the functionality of filter_* and regexs are very loosely correlated. Most likely, a regex can be crafted to do the job of a filter_* function, but it doesn't work the other way around. So, regexes bring increased functionality and flexibility to the table while also being more complex.

Personally, when dealing with simple inputs (integers, dates, times), I use a filter_* function, while more complex inputs or very specific or custom inputs (custom identifier that should start and end with a letter and have 3 digits in between) are more suited for a regex.

like image 180
nickb Avatar answered Jan 18 '23 22:01

nickb


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.

like image 24
DonSeba Avatar answered Jan 19 '23 00:01

DonSeba