Link to home
Start Free TrialLog in
Avatar of gorrie67
gorrie67

asked on

PHP preg_replace for Time

I need a PHP function[s] (? preg_replace) that will convert different entered time formats to the standard hh:mm.
Possible entered formats include:
hh:mm
h:mm
hh.mm
h.mm
hhmm
hmm
h
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Something like this should work a treat for all your examples. Will test it shortly.
$patterns = array("/^(\d)\D?(\d\d)$/", #one digit hour
                  "/^(\d\d)\D?(\d\d)$/", #two digit hour
                  "/^(\d)$/");
$replacements = array("0$1:$2",
                      "$1:$2",
                      "$1:00");
$result = preg_replace($patterns, $replacements, $time);

Open in new window

It passed testing as is with your example data. To wrap it in a function:
function to_std_time($time) {
  $patterns = array("/^(\d)\D?(\d\d)$/", #one digit hour
                    "/^(\d\d)\D?(\d\d)$/", #two digit hour
                    "/^(\d)$/");
  $replacements = array("0$1:$2",
                        "$1:$2",
                        "$1:00");
  return preg_replace($patterns, $replacements, $time);
}

Open in new window

Of course you might like to add criteria to handle invalid formats too.
Avatar of gorrie67
gorrie67

ASKER

Thanks TerryAtOpus

All works fine, except for inputs of hh only, ie 8, 12, 13

these need to be formatted to hh:mm, ie 08:00, 12:00, 13:00

Can this be added to function?
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial