robsim Posted April 9, 2010 Share Posted April 9, 2010 Hello, Could someone help me with a regular expression? I ask users to input time in the form HH:MM:SS (e.g 14:32:53 or 0:22:10). So the regex should check that the time has been entered correctly, with ":" and minutes and seconds cannot be bigger than 60. Thanks a lot in advance! Quote Link to comment Share on other sites More sharing options...
TeddyKiller Posted April 9, 2010 Share Posted April 9, 2010 $date("H:i:s", time()); This will display the current time in hours, minutes and seconds. Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 9, 2010 Share Posted April 9, 2010 Perhaps this ... <?php $input = "14:32:53"; preg_match("#^((0?[0-9])|(1[0-9])|(2[0-3]))((0?[0-9])|([1-5][0-9]))){2}$#", $input, $match); * not tested, but you get the general idea, right? Quote Link to comment Share on other sites More sharing options...
TeddyKiller Posted April 9, 2010 Share Posted April 9, 2010 Ah, yeah that could be what ken2K7 put. I read the initial question wrong. Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 9, 2010 Share Posted April 9, 2010 I took what Ken2k7 posted and fixed it. This is tested: function validTime($time) { return preg_match("/^((0?[0-9])|(1[0-9])|(2[0-3]))(:[0-5][0-9]){2}$/", $time); } To be valid the time must follow the following parameters: The beginning must be one of the following (0-9) (any single digit number) 0(0-9) (0 followed by any single digit number) 1(0-9) (1 followed by any single digit number) 2(0-3) (2 followed by 0, 1, 2 or 3) There must then be a colon followed by (0-5)(0-9) (first digit a 0, 1, 2, 3, 4, or 5, second digit any number) Then another colon followed by (0-5)(0-9) (first digit a 0, 1, 2, 3, 4, or 5, second digit any number) One problem with the above is that it accepts 00:00:00 but not 24:00:00. Some people prefer one over the other. If you need to support 24:00:00, then change the regex to this: /^(((0?[0-9])|(1[0-9])|(2[0-3]))(:[0-5][0-9]){2})|(24:00:00)$/ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.