March 7, 2013
Replacing characters only a set amount of time
Question by William N
I’ve been googling a bit, but I can’t figure out what keywords to use.
I’m saving the users date of birth, and I want to make sure the format is YYYY-MM-DD.
I’m thinking something like:
if(!ctype_digit(str_replace("-", "", $dob)) || strlen(str_replace("-", "", $dob)) != 8)
{
echo "Incorrect format: date of birth";
}
For this, I need to use strlen() to only replace three – chars. If it’s more or less than 3, then echo incorrect format. How do I achieve this? Or is there a better way?
Answer by Starx
How about using regex?
if ( !preg_match( "/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $dob) )
{
echo "Invalid date.";
}