filter_var using FILTER_VALIDATE_REGEXP

早过忘川 提交于 2019-11-30 22:33:43

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/10993451/filter-var-using-filter-validate-regexp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!