正则表达式用于时间验证

时间:2012-07-02 15:20:06

标签: php regex time

我想用正则表达式验证时间。我创建了以下表达式:

'#^([01][0-9])|(2[0-4])(:[0-5][0-9]){1,2}$#'

问题在于:

<?php
var_dump(preg_match('#^([01][0-9])|(2[0-4])(:[0-5][0-9]){1,2}$#', '14:25'));
// Returns 1 (OK)

var_dump(preg_match('#^([01][0-9])|(2[0-4])(:[0-5][0-9]){1,2}$#', '25:25'));
// Returns 0 (OK)

var_dump(preg_match('#^([01][0-9])|(2[0-4])(:[0-5][0-9]){1,2}$#', '14:2555'));
// Returns 1 (instead of 0 as I would like to get)
?>

有人知道出了什么问题吗?

4 个答案:

答案 0 :(得分:21)

24小时格式正则表达式模式的时间:

([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?

24小时时钟格式从0-23或00-23开始,然后是半冒号(:)然后是00-59然后(可选择半分号(:),然后是00-59)。

描述:

(                  # start of group #1
  [01]?[0-9]       # start with 0-9,1-9,00-09,10-19
  |                # or
  2[0-3]           # start with 20-23
)                  # end of group #1
:                  # follow by a semi colon (:)
[0-5][0-9]         # follow by 0..5 and 0..9, which means 00 to 59
(                  # start of group #2
  :                # follow by a semi colon (:)
  [0-5][0-9]       # follow by 0..5 and 0..9, which means 00 to 59
)                  # end of group #2
?                  # optional third part

匹配时间格式:

01:00, 02:00, 13:00,
 1:00,  2:00, 13:01,
23:59, 15:00,
00:00,  0:00,
14:34:43, 01:00:00

不符合时间格式:

 24:00             # hour is out of range [0-23]
 12:60             # minute is out of range [00-59]
  0:0              # invalid format for minute, at least 2 digits
 13:1              # invalid format for minute, at least 2 digits
  0:00:0           # invalid format for seconds, at least 2 digits
101:00             # hour is out of range [0-23]

示例:

var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '14:25'));    // OK
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '25:25'));    // KO
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '25:30'));    // KO
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '14:2555'));  // KO
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '14:65'));    // KO
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '14:59'));    // OK
var_dump(preg_match('#^[01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$#', '14:34:43')); // OK

答案 1 :(得分:5)

^(([0-1][0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?)$

这将从00:00到23:59和00:00:00到23:59:59。

答案 2 :(得分:2)

Alternation是一个低优先级运算符,因此将其包装在非捕获组中:

    #^(?:([01][0-9])|(2[0-3]))(:[0-5][0-9]){1,2}$#
      +++                    +

请参阅演示here

答案 3 :(得分:1)

/(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?/

这将允许00:00或00:00:00,其他一些不允许。

它还将时间限制在00:00:00到23:59:59或23:59,其他一些允许24:00或25:00等等。