filter_var using FILTER_VALIDATE_REGEXP
27,141
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
![Iris](https://i.stack.imgur.com/I6oF4.jpg?s=256&g=1)
Comments
-
Iris about 4 years
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; }
-
Iris about 12 yearsWhen I use preg_match() instead it works fine...
-
Anthony Rutledge over 9 yearspreg_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.
-
Cyclonecode over 5 yearsWhy don't people read the documentation?
-
-
Iris about 12 yearsReally? 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.
-
Cranio about 12 yearsFor 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.