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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!