How to check data format in PHP

I am trying to check the date format to see if I can check the data variable in a specific format, such as MM-DD-YYYY. if not, then exit (). I am not sure how to check the format and would appreciate it if anyone could help me. Thank...

$date=05/25/2010;    
if(XXXXX){
    // do something....
}
+3
source share
6 answers

Use regex as others have suggested. However, those that are sent will accept invalid dates, such as 99/99/9999. Here's an improved regex (from here )

$date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';
if (preg_match($date_regex, $date)) {
   // do something
}

It will only accept valid dates, and it will also accept various delimiters (for example, 05.20.2002 and 05-02-2002).

, , . , strtotime().

+2

if(preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/"))
{
    do something
} 
+4

, , strtotime() unix, date(), , .

, , preg_match() , , . :

if (preg_match('~[0-9]{2}-[0-9]{2}-[0-9]{4}~', $dateStr)) { echo 'Correct format'; }

, , . -, strtotime/date, .

+2

, , , MM-DD-YYYY?

, : , , , , , , - .

function checkDate( $date )
{

    if (preg_match("/[0|1][0-9]/[0-9][1-9]/[0-9]{4}/",$date)
    {
        if (substr($date,0,2)<=12 && substr($date,3,2)<=31)
        {
             return true;
        }
    }
    return false

}

: ​​ , , , NullUser

+1

Source: https://habr.com/ru/post/1756351/


All Articles