filter_var using FILTER_VALIDATE_REGEXP
Asked Answered
L

1

15

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;
}
Leahy answered 12/6, 2012 at 9:2 Comment(2)
When I use preg_match() instead it works fine...Leahy
preg_match() would require you to use a callback filter. If you want to use the PHP filter mechanism (which is operating a bit differently than using superglobals), just create an associative array like in the manual examples.Ruffianism
D
30

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

Drama answered 12/6, 2012 at 9:26 Comment(4)
Really? That's not very clear from the documentation in the php manual :-/ Thanks also for the regex tips :) I'll fiddle around with this a bit.Leahy
For regular expressions in general, and in PHP, you may give a look to: regular-expressions.info/tutorial.html and regular-expressions.info/php.html this site helped me a lot.Drama
you should use /^[a-zA-Z\s]+$/ as pattern, otherwise things like john+1 will come out as valid. I think your pattern validates anything that contains at least one aplhabet/space character. The pattern I give validates that ALL characters are aplhabetic/spaces. See: #36422188Ruiz
The capture group is not beneficial. 3v4l.org/sBC8OAntisemite

© 2022 - 2024 — McMap. All rights reserved.