【问题标题】:filter_var using FILTER_VALIDATE_REGEXPfilter_var 使用 FILTER_VALIDATE_REGEXP
【发布时间】:2012-06-15 03:30:08
【问题描述】:

我正在练习我的初学者 php 技能,想知道为什么这个脚本总是返回 FALSE?

我做错了什么?

$namefields = '/[a-zA-Z\s]/';

$value = 'john';

if (!filter_var($value,FILTER_VALIDATE_REGEXP,$namefields)){
    $message = 'wrong';
    echo $message;
}else{
    $message = 'correct';
    echo $message;
}

【问题讨论】:

  • 当我使用 preg_match() 代替它工作正常...
  • preg_match() 将要求您使用回调过滤器。如果您想使用 PHP 过滤器机制(其操作与使用超全局变量有点不同),只需创建一个关联数组,就像在手动示例中一样。
  • 为什么人们不阅读文档?

标签: php filter-var


【解决方案1】:

正则表达式应该在一个选项数组中。

$string = "Match this string";

var_dump(
    filter_var(
        $string, 
        FILTER_VALIDATE_REGEXP,
        array(
             "options" => array("regexp"=>"/^M(.*)/")
        )
    )
); // <-- look here

另外,

$namefields = '/[a-zA-Z\s]/';

应该比较

$namefields = '/[a-zA-Z\s]*/'; // alpha, space or empty string

$namefields = '/[a-zA-Z\s]+/'; // alpha or spaces, at least 1 char

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 2012-11-24
  • 2012-01-15
  • 1970-01-01
  • 2011-01-09
  • 2012-01-08
  • 1970-01-01
相关资源
最近更新 更多