date() is malfunctioning

i have a php methode that checks if a passed in parameter is a date. Here's it:

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

then, i test-drove it like this:

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

Note that each of the ifs also has an else statement as in :

else{
   echo $var.' '.'is not a date' 
}

OUTPUT:

100% is a Date
31/03/1970 is a Date
31/03/2005 is a Date
31/03/1985 is a Date

My problem is, why is 100% displaying as a date and why is 31/03/1985 not being read as a date ?

Any clue as to why will be highly appreciated as i am not too expertise in Regex


You are using ^ at end of regex string, Meaning of ^ is to compare beginning of string.

Also, as hjpotter92 suggested, you could simply use is_numeric(strtotime($str))

Your function should look like:

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

Documentation says:

Dates in the m/d/y or dmy formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European dmy format is assumed.


i'd got it working now ! the new output has stoped displaying 100% as a date, which was what i planned.here's the final code sippette that does the job:

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 !
链接地址: http://www.djcxy.com/p/23906.html

上一篇: 卡夫卡消费者会议超时

下一篇: 日期()发生故障