php filter_var 使用 FILTER_VALIDATE_REGEXP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10993451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:33:05  来源:igfitidea点击:

filter_var using FILTER_VALIDATE_REGEXP

phpfilter-var

提问by Iris

I'm practicing my beginner php skills and would like to know why this script always returns FALSE?

我正在练习我的初学者 php 技能,想知道为什么这个脚本总是返回 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;
}

回答by Cranio

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

因为第一个版本我认为你只匹配单字符串