filter_var using FILTER_VALIDATE_REGEXP

Iris picture Iris · Jun 12, 2012 · Viewed 25.7k times · Source

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;
}

Answer

Cranio picture Cranio · Jun 12, 2012

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