Re: regexp novice

From: Date: Fri, 18 May 2012 02:49:02 +0000
Subject: Re: regexp novice
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-317887@lists.php.net to get a copy of this message
On 5/17/2012 1:57 PM, shiplu wrote:
On Fri, May 18, 2012 at 2:37 AM, 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?
I can not correct your regexp. But I must tell you that trying to tweak a regex for hours is surely **not productive**. If you got any type of text processing dont always go for regular expression. This problem can be solved just by simple string parsing. Here I have done that for you. function valid_time($time){
         $m  = (int) substr($time, -2);
         $h  = (int) substr($time, 0, -2);
         return ($h>=0&&  $h<13&&  $m>=0&&  $m<60);
}
That won't work, it doesn't account for the possibility of a single digit hour field. I would do something like this: <?php $times = array(
        '100',          # valid
        '1100',         # valid
        '1300',         # invalid
        '01:00',        # valid
        '12:59',        # valid
        '00:01',        # valid
        '00:25pm',      # invalid
        '0000',         # valid
        'a00',          # invalid
        '00',           # invalid
        );
foreach ( $times AS $time )
        echo "{$time} is ".(valid_date($time)?'valid':'invalid')."\n";
function valid_date($time) { if ( ( $c_time = preg_replace('|[^\d:]+|', '', $time) ) !== $time )
    return false;
if ( ( $pos = strpos($c_time, ':') ) !== false ) {
    list($hour, $minute) = explode(':', $c_time, 2);
} else {
    $break  = (strlen($c_time) - 2);
    $hour   = substr($c_time, 0, $break);
    $minute = substr($c_time, $break, 2);
} $hour = (int)$hour; $minute = (int)$minute; if ( strlen($c_time) <= 2 )
    return false;
if (
    ( $hour   >= 0 && $hour   <= 12 ) &&
    ( $minute >= 0 && $minute <= 59 )
      ) {
    return true;
} return false; } It seems overly complicated, but it does check and error for the various things that I could think of for possible input. Give it a try and let us know. See it in action here. http://cmsws.com/examples/php/testscripts/shiplu.net@gmail.com/pt.php http://cmsws.com/examples/php/testscripts/shiplu.net@gmail.com/pt.phps Jim Lucas

« previous php.general (#317887) next »