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 d-m-y 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 d-m-y format is assumed.
I'd got it working now! the new output has stopped displaying 100% as a date, which was what I planned. Here's the final code snippet 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 !";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With