Validate time format using preg_match

后端 未结 3 1808
离开以前
离开以前 2020-12-11 12:38

I want to validate a time input (like 10:30 am, 02:30 pm) using preg_match()

I use this,

 $pattern   =   \"/([1-12]):([0-5])([0-9])( )(a         


        
相关标签:
3条回答
  • 2020-12-11 12:57

    REGEX SOLUTION

    • [1-12] will not work, because this is not range definition, but [ and ] means start and end character class definition.
    • use /i pattern modifier at end, so you don't need to write PM, pm, pM, Pm, AM, am, aM, Am combinations.
    • PM and AM fetch can bi simpleffied with [ap]m.
    • if you wish to validate whole string, then the string must be valid from the start to end with ^ and $.
    • I added \h escape sequence (horizontal whitespace char) between time and pm|am, so time like 10:10am can be valid to.

    Code:

    $time = '10:30 am';
    $pattern = '~^(0[0-9]|1[0-2]):([0-5][0-9])\h*([ap]m)$~i';
    if (preg_match($pattern, $time, $m)) {
        print_r($m);
        return true;
    }
    

    Output

    Array
    (
        [0] => 10:30 am
        [1] => 10
        [2] => 30
        [3] => am
    )
    
    0 讨论(0)
  • 2020-12-11 13:02

    DATETIME SOLUTION

    You can validate all your date/time strings with DateTime::createFromFormat:

    Function

    function isTimeValid($time) {
        return is_object(DateTime::createFromFormat('h:i a', $time));
    }
    

    Example

    foreach (['12:30 am', '13:30 am', '00:00 pm', '00:00 am', '12:30am', '15:50pm'] as $time) {
        echo "Time '$time' is " . (isTimeValid($time) ? "" : "not ") . "valid.\n";
    }
    

    Example output

    Time '12:30 am' is valid.
    Time '13:30 am' is not valid.
    Time '00:00 pm' is valid.
    Time '00:00 am' is valid.
    Time '12:30am' is valid.
    Time '15:50pm' is not valid.
    
    0 讨论(0)
  • 2020-12-11 13:06

    The [...] notation in regexes defines character class: something that's applied to the single character. It's alternation that should be used here instead:

    0[1-9]|1[0-2]
    

    ... so the regex in whole would look like this:

    /^(?:0[1-9]|1[0-2]):[0-5][0-9] (am|pm|AM|PM)$/
    
    0 讨论(0)
提交回复
热议问题