FILTER_VALIDATE vs Preg_match. Which one to use?

南笙酒味 提交于 2019-12-04 10:59:12

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.

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.

You should definitely use filter. It is made specifically for validation. A regular expression is always custom and if you write it yourself, you can forget many things which need to be checked.

Both are doing the same thing but filters would seem to be the simpler and nicer option to use, you could also use value ranges if you wanted.

If you wanted to do something other that just check for a valid number and a bit more complex involving strings also then using a regular expression might be the way to go however.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!