filter_var using FILTER_VALIDATE_REGEXP

2019-02-16 08:56发布

问题:

I'm practicing my beginner php skills and would like to know why this script always returns FALSE?

What am i doing wrong?

$namefields = '/[a-zA-Z\s]/';

$value = 'john';

if (!filter_var($value,FILTER_VALIDATE_REGEXP,$namefields)){
    $message = 'wrong';
    echo $message;
}else{
    $message = 'correct';
    echo $message;
}

回答1:

The regexp should be in an options array.

$string = "Match this string";

var_dump(
    filter_var(
        $string, 
        FILTER_VALIDATE_REGEXP,
        array(
             "options" => array("regexp"=>"/^M(.*)/")
        )
    )
); // <-- look here

Also, the

$namefields = '/[a-zA-Z\s]/';

should be rather

$namefields = '/[a-zA-Z\s]*/'; // alpha, space or empty string

or

$namefields = '/[a-zA-Z\s]+/'; // alpha or spaces, at least 1 char

because with the first version I think you match only single-character strings