Re: regexp novice

From: Date: Fri, 18 May 2012 05:31:56 +0000
Subject: Re: regexp novice
References: 1 2 3 4 5  Groups: php.general 
Request: Send a blank email to php-general+get-317890@lists.php.net to get a copy of this message
On 5/17/2012 9:52 PM, Jim Lucas wrote:
How about this instead? <pre><?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; preg_match('#^(?P<hour>\d{1,2}):?(?P<minute>\d{2})$#', $time, $m); if ( $m && ( 0 <= (int) $m['hour'] && 12 >= (int) $m['hour'] ) && ( 0 <= (int) $m['minute'] && 59 >= (int) $m['minute'] ) ) { return TRUE; } return false; } Let me know.
I optimized it a little... http://www.cmsws.com/examples/php/testscripts/shiplu.net@gmail.com/pt_regex.php http://www.cmsws.com/examples/php/testscripts/shiplu.net@gmail.com/pt_regex.phps <pre><?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_time($time)?'valid':'invalid')."\n"; function valid_time($time) { if (
      preg_match('#^(\d{1,2}):?(\d{2})$#', $time, $m) &&
      ( 0 <= (int) $m[1] && 12 >= (int) $m[1] ) &&
      ( 0 <= (int) $m[2] && 59 >= (int) $m[2] )
     ) {
    return TRUE;
} return FALSE; }

« previous php.general (#317890) next »