简体   繁体   中英

regular expression not working when check time in php

below is my code for checking the variable is either time or not

function isTime($time) {

    if (preg_match("/^([1-2][0-3]|[01]?[1-9]):([0-5]?[0-9]):([0-5]?[0-9])$/", $time))
            {
        return true;
            echo "<script>alert('is a time');</script>";
            }
         else {
            echo "<script>alert('not a time');</script>";
           return false;
           }
         }

and this is expression fails when value like this $time=00:08:33 , and working fine with time like $time=01:08:33 , please modify this expression

You need to change [01]?[1-9] pattern inside the first capturing group to [01]?[0-9] , so that it would also matches the number 00 . [1-9] Matches all the digits which falls within this range ( 1 to 9 ), and [0-9] matches all the digits from 0 to 9.

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

DEMO

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM