Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter_var using FILTER_VALIDATE_REGEXP

Tags:

php

filter-var

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;
}
like image 261
Iris Avatar asked Jun 12 '12 09:06

Iris


People also ask

What is Filter_validate_regexp?

The FILTER_VALIDATE_REGEXP filter validates value against a Perl-compatible regular expression. Name: "validate_regexp"

What is the use of the Filter_var () and Filter_input () functions in PHP?

filter_var. If a variable doesn't exist, the filter_input() function returns null while the filter_var() function returns an empty string and issues a notice of an undefined index.

What is filter_ VALIDATE_ email in PHP?

The FILTER_VALIDATE_EMAIL filter validates an e-mail address.


1 Answers

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

like image 136
Cranio Avatar answered Oct 13 '22 10:10

Cranio