is_date()发生故障

Osa*_*gie 7 php regex date

我有一个PHP方法,检查传入的参数是否是一个日期.这是它:

public function is_Date($str){ 
        if (is_numeric($str) ||  preg_match('^[0-9]^', $str)){  
            $stamp = strtotime($str);
            $month = date( 'm', $stamp ); 
            $day   = date( 'd', $stamp ); 
            $year  = date( 'Y', $stamp ); 
            return checkdate($month, $day, $year); 
        } 
        return false; 
}
Run Code Online (Sandbox Code Playgroud)

然后,我测试开它像这样:

$var = "100%";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
} 

$var = "31/03/1970";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}

$var = "31/03/2005";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}

$var = "31/03/1985";

if(is_Date($var)){
   echo $var.' '.'is a date'; 
}
Run Code Online (Sandbox Code Playgroud)

请注意,每个ifs还有一个else语句,如:

else{
   echo $var.' '.'is not a date' 
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

100% is a Date
31/03/1970 is a Date
31/03/2005 is a Date
31/03/1985 is a Date
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么100%显示为日期,为什么31/03/1985不被视为日期?

关于为什么的任何线索将受到高度赞赏,因为我不是在Regex中的专业知识

Rav*_*a ツ 5

^在正则表达式字符串的末尾使用,意思^是比较字符串的开头

另外,正如hjpotter92建议的那样,您可以简单地使用is_numeric(strtotime($str))

您的函数应如下所示:

public function is_Date($str){ 
    $str=str_replace('/', '-', $str);  //see explanation below for this replacement
    return is_numeric(strtotime($str)));
}
Run Code Online (Sandbox Code Playgroud)

文档说:

m/d/ydmy格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲dmy格式。

  • `^` OP 是分隔符,你已经在 `preg` 函数中忘记了它。 (3认同)

Osa*_*gie 2

我现在就可以使用了!新输出已停止将 100% 显示为日期,这正是我的计划。这是完成这项工作的最终代码片段

public function is_Date($str){ 
    $str = str_replace('/', '-', $str);     
    $stamp = strtotime($str);
    if (is_numeric($stamp)){  
       $month = date( 'm', $stamp ); 
       $day   = date( 'd', $stamp ); 
       $year  = date( 'Y', $stamp ); 
       return checkdate($month, $day, $year); 
    }  
    return false; 
}
echo "A million thanks to you all ! you guys are the best !";
Run Code Online (Sandbox Code Playgroud)