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;
}
The FILTER_VALIDATE_REGEXP filter validates value against a Perl-compatible regular expression. Name: "validate_regexp"
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.
The FILTER_VALIDATE_EMAIL filter validates an e-mail address.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With