Filter_var vs preg_match

Morning all

I am converting a site that I am working on to be compatible with the latest version of PHP, so I look through and replace all ereg instances with their non-depreciated equivalent. However, I was told about a convenient built-in function with PHP called filter_var.

What is my question, does it make sense to go with filter_var over preg_match? As in the case of increased productivity or any other advantages for choosing one over the other, and if so, what are they?

+3
source share
3 answers

filter_var - Filters a variable with a given filter
preg_match - execute a regular expression matching

, filter_var , preg_match. , ereg, filter_var , / .

+2

, PHP : https://php.net/manual/en/book.filter.php

, . , ( ) . , HTTP-/ PHP, .

filter_input $_SERVER, $_COOKIE, $_POST $_GET. "where" , , $_POST, $_GET, $_COOKIE $_SERVER. , /, $_GET, $_POST $_SERVER, . , . (, , ..) . $_POST, $_GET $_SERVER. , $_FILES.

filter_var , . filter_input. , , .

FILTER_VALIDATE_REGEXP , , , preg_match(). , "n" /, , .

, , , . , , , ( ). , , . , -.

, .

, . , PHP , , , , ( , -, ). .

, preg_match(), (filter_input ) . , $_SERVER, $_POST $_GET. , , , , (FILTER_CALLBACK) , , / ( ). , , FILTER_VALIDATE_REGEXP, , , , . ? . , .

+3

filter_var() . , . , , , , filter_var().

, :

if (eregi('\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b', $_POST['email'])) {
    echo "valid";
}

( ):

if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "valid";
}

filter_var() sanitize , , , ( ):

$clean = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

filter_var() ereg_replace().

However, for the simplest update, you can simply “prefix” the ereg * () family of functions with “p”, which makes them compatible with PCRE (and therefore no longer deprecated in PHP 5.3+).

+1
source

Source: https://habr.com/ru/post/1719731/


All Articles