Re: regexp novice

From: Date: Fri, 18 May 2012 22:00:09 +0000
Subject: Re: regexp novice
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-317906@lists.php.net to get a copy of this message
On Thu, May 17, 2012 at 3:37 PM, Jim Giner <jim.giner@albanyhandball.com> wrote: > ok - finally had to come up with my own regexp - and am failing. > > Trying to validate an input of a time value in the format hh:mm, wherein > I'll accept anything like the following: > hmm > hhmm > h:mm > hh:mm > > in a 12 hour format.  My problem is my test is ok'ing an input of 1300. > > Here is my test: > >  if (0 == preg_match("/([0][1-9]|[1][0-2]|[1-9]):[0-5][0-9]/",$t)) >    return true; > else >    return false; > > Can someone help me correct my regexp? If the ":" separator is inserted before the regex check, the following should suffice: '/^(0?[1-9]|1[12]):([0-5][0-9])$/' Test script: <?php $testvalues=array("1:00","2:30","12:50","11:00", "13:00","1:69", "01:00","12:59pm","00:40","00:00","a:00","00"); $valid_re = '/^(0?[1-9]|1[12]):([0-5][0-9])$/'; foreach ($testvalues as $time) { if (preg_match($valid_re,$time)) { echo "$time passes\n"; } else { echo "$time fails\n"; } } Produces output: php twelvehourtimecheck.php 1:00 passes 2:30 passes 12:50 passes 11:00 passes 13:00 fails 1:69 fails 01:00 passes 12:59pm fails 00:40 fails 00:00 fails a:00 fails 00 fails

« previous php.general (#317906) next »