Re: regexp novice

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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@xxxxxxxxx/pt_regex.php
http://www.cmsws.com/examples/php/testscripts/shiplu.net@xxxxxxxxx/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;
}


--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux