php 验证此格式 - “HH:MM”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3964972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:35:17  来源:igfitidea点击:

validate this format - "HH:MM"

phpregexpreg-match

提问by Catfish

I'm trying to use preg_matchto validate that a time input is in this format - "HH:MM"

我试图用来preg_match验证时间输入是否采用这种格式 - “HH:MM”

回答by Charles

You can use regular expressions to check that.

您可以使用正则表达式来检查。

for 12-hour:

12 小时:

preg_match("/^(?:1[012]|0[0-9]):[0-5][0-9]$/", $foo)

for 24-hour:

24 小时:

preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $foo)

If you use a 24-hour clock going from 01:00to 24:59, use

如果您使用从01:0024:59的 24 小时制,请使用

preg_match("/^(?:2[0-4]|[01][1-9]|10):([0-5][0-9])$/", $foo)

回答by T30

Simple function that validates a date (and/or time) without throwing exceptions. It takes the expected date formatas a parameter:

验证日期(和/或时间)而不抛出异常的简单函数。它将预期的日期格式作为参数:

function isValidDate(string $date, string $format = 'Y-m-d'): bool
{
    $dateObj = DateTime::createFromFormat($format, $date);
    return $dateObj && $dateObj->format($format) == $date;
}

How it works: it converts the input date into a PHP DateTimeobject according to the passed $format, then compares this object with the original input date. If they match, the date is valid and has the expected format.

它是如何工作的:它DateTime根据传递的将输入日期转换为 PHP对象$format,然后将此对象与原始输入日期进行比较。如果它们匹配,则日期有效并且具有预期的格式。

Some usage examples:

一些使用示例:

/* Valid Examples: */
isValidDate("2017-05-31");
isValidDate("23:15:00", 'H:i:s');
isValidDate("2017-05-31 11:15:00", 'Y-m-d h:i:s');

/* Invalid: */
isValidDate("2012-00-21");
isValidDate("25:15:00", 'H:i:s');
isValidDate("Any string that's not a valid date/time");

回答by Toskan

Let's imagine the time you want to check is $timeStrand has to be the format H:iaccording to the date specs. Using a regex for this is IMHO silly. This is so much easier to read:

让我们想象一下您要检查的时间是$timeStr并且必须是H:i根据日期规范的格式。为此使用正则表达式是愚蠢的。这更容易阅读:

UPDATED

更新

$timeStr = " 02:00"; //example of valid time, note whitespace
test($timeStr);
$timeStr = "23:59"; //valid
test($timeStr);
$timeStr = "24:00"; //invalid
test($timeStr);
$timeStr = "25:00"; //invalid
test($timeStr);    
$timeStr = "16:61"; // invalid
test($timeStr);

//tests 23:59 hour format
    function test($timeStr){

    $dateObj = DateTime::createFromFormat('d.m.Y H:i', "10.10.2010 " . $timeStr);

    if ($dateObj !== false && $dateObj && $dateObj->format('G') == 
        intval($timeStr)){
        //return true;
        echo 'valid  <br/>';
    }
    else{
      //return false;
      echo 'invalid <br/>';
    }

}

回答by zion ben yacov

here is a code that check if the string is an hour between 00:00 and 23:59

这是一个代码,用于检查字符串是否为 00:00 和 23:59 之间的一个小时

$checked = false;
    if (preg_match('/^\d{2}:\d{2}$/', $str)) {
        if (preg_match("/(2[0-3]|[0][0-9]|1[0-9]):([0-5][0-9])/", $str)) {
            $checked = true;
        }
    }
    var_dump($checked );die;

回答by Steve M.

For a 12-hour match that can do am and pm, use this

对于可以进行 am 和 pm 的 12 小时比赛,请使用此

/^(1[0-2]|0?[1-9]):[0-5][0-9] (AM|PM)$/i

It will handle 01:20 am or 1:20 AM. The examples above for 12 hour were incorrect because you could potentially do:

它将处理上午 01:20 或凌晨 1:20。上面 12 小时的示例不正确,因为您可能会这样做:

00:20

which is not a valid 12 hour format.

这不是有效的 12 小时格式。

回答by codaddict

You can do:

你可以做:

if(preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$input)) {
        // $input is valid HH:MM format.
}

回答by user2430012

Expanding on what @Toskan wrote, you could do this to validate in 00:00 format. Returns true if valid and between 00:00 and 23:59.

扩展@Toskan 所写的内容,您可以这样做以验证 00:00 格式。如果有效且介于 00:00 和 23:59 之间,则返回 true。

This also allows different time formats to be used...

这也允许使用不同的时间格式......

function isTimeValid($time_str, $format = 'H:i')
{
    $DateTime = \DateTime::createFromFormat( "d/m/Y {$format}", "10/10/2010 {$time_str}" );
    return $DateTime && $DateTime->format( "d/m/Y {$format}" ) == "10/10/2010 {$time_str}";
}

回答by TILiBRA

Function that validates hours, minutes and seconds, according to the desired format:

根据所需格式验证小时、分钟和秒的函数:

function validTime($time, $format='H:i:s') {
    $d = DateTime::createFromFormat("Y-m-d $format", "2017-12-01 $time");
    return $d && $d->format($format) == $time;
}


How to use:

如何使用:

$valid = validTime("23","H");
$valid = validTime("23:59","H:i");
$valid = validTime("23:59:59","H:i:s");
$valid = validTime("23:59:59");

valid = true

有效 = 真

$valid = validTime("25","H");
$valid = validTime("01:60","H:i");
$valid = validTime("01:20:61","H:i:s");
$valid = validTime("01:20:61");

valid = false

有效 = 假

回答by Vladislav Savchuk

Based on the Charles's elegant answer with regular expression. If you need a one line validation of both "HH:MM"and "H:MM"(i.e. "9:45"/"09:45") use the following regexp to match 24-hour format:

基于查尔斯用正则表达式给出的优雅答案。如果您需要对"HH:MM""H:MM"(即"9:45"/ "09:45")进行一行验证,请使用以下正则表达式来匹配 24 小时格式:

preg_match("/^(?(?=\d{2})(?:2[0-3]|[01][0-9])|[0-9]):[0-5][0-9]$/", $time)

Explanation

解释

(?stands for conditional subpattern, the syntax is:

(?代表条件子模式,语法是:

(?(condition)yes-pattern|no-pattern)

(?(条件) yes-pattern| no-pattern)

?=in conditionis the regexp assertion

?=条件正则表达式断言

?:in yes-patternis optionalfor better performance and you may drop it. This means we don't need any capturingwithin parentheses (), we need just alternatives feature.

?:yes-pattern 中可选的以获得更好的性能,你可以放弃它。这意味着我们不需要括号内的任何捕获(),我们只需要替代功能。

So, we merely describe the following:

因此,我们仅描述以下内容:

  1. If $timestring begins with two digits (?=\d{2}), use (2[0-3]|[01][0-9])pattern to match HH-hour notation ("09:45"case)
  2. otherwise use [0-9]pattern to match H-hour notation ("9:45"case)
  1. 如果$time字符串以两位数字开头(?=\d{2}),则使用(2[0-3]|[01][0-9])模式匹配 HH 小时表示法("09:45"大小写)
  2. 否则使用[0-9]模式来匹配 H 小时符号("9:45"大小写)

UPDATE

更新

As they say, simplicity is the sister of a talent. We don't necessarily need the condition pattern described above. The simpler validation of "HH:MM/H:MM"for 24-hourformat:

正如他们所说,简单是人才的姐妹。我们不一定需要上述条件模式。较简单的验证"HH:MM/H:MM"24小时格式:

preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $time)

Again, ?:in grouping parentheses ()is optional to disable capturing, you can drop it.

同样,?:在分组括号()中禁用捕获是可选的,您可以删除它。

So, in this regexp the alternative subpatterns withing ()is trying to match two digits hour at the first (20..23) and second (01..19) pattern, then one digit at the last third one (0..9).

所以,在这个正则表达式中,替代子模式 withing()试图在第一个 ( 20..23) 和第二个 ( 01..19) 模式匹配两位数字小时,然后在最后第三个 ( 0..9)匹配一位数字。

In addition, the validation of "HH:MM/H:MM"for 12-hourformat:

此外,"HH:MM/H:MM"对于12 小时格式的验证:

preg_match("/^(?:0?[1-9]|1[012]):[0-5][0-9]$/", $time);

Here, we're trying to match at first one digit (1..9) with possible preceding zero (0?), and then two digits (10..12).

在这里,我们尝试首先匹配一位数字 ( 1..9) 与可能的前导零 ( 0?),然后匹配两位数字 ( 10..12)。

回答by Roshimon

If you're looking for seconds (24hour). This worked like a charm for me.

如果您正在寻找秒(24 小时)。这对我来说就像一种魅力。

$time = "23:59:60";    
preg_match("/^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $time)