Preg_match (yyyy-mm-dd hh:mm:ss) - only this format

16,677

Solution 1

Add start ^ and end $ anchors to your regex.

if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/", $date_time))

Solution 2

 ^  Start of string or line  
\A  Start of string  
 $  End of string or line  
\Z  End of string  

Try to put some of these anchor characters in the code:

preg_match("/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/", $date_time)

You can find more basic characters for regexp here.

Solution 3

Add anchors to your regex:

 if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/", $date_time))
Share:
16,677
Kavvson
Author by

Kavvson

Updated on June 13, 2022

Comments

  • Kavvson
    Kavvson almost 2 years
    function Check_Date_Time($date_time)
    {
     if (preg_match("/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/", $date_time))
       {
         return true;
       }
         else 
         {
         return false;
         }
    }   
    
    if(Check_Date_Time($date)){
        //echo 'correct';
    }else{
        die();
    }
    

    If I set the date as such

    ["DueDate3"]=> string(24) "2014-10-17 21:10:1751111" 
    

    the validator let its trough, I got no ideas why :/ If it is a properly used date format it returns true. I don't really can use other formats - only this is acceptable

  • Book Of Zeus
    Book Of Zeus about 5 years
    Please explain your answer, regex might not be easy to understand for everyone
  • vanquan223
    vanquan223 about 5 years
    This returns true for a number of invalid dates like 2016-02-30 and 2016-09-31. You can use a preg_match with a checkdate php function link