Regex Fun

Last week we discovered how to better split up time strings that people might enter. I want the time inputs to be very flexible–anything from “12:00PM”, “523”, “4p”, etc. The regex that we ended with was something along the lines of:

([0-9][0-9]?):?([0-9][0-9]?)?[\s]?(am|pm|a|p|h)?

Which was good! But for values like 110 it would return the chunks 10 and 0, instead of 1 and 00. So I worked with it a bit and settled on the following regex:

([0-9])([0-9])?:?([0-9])?([0-9])?[\s]?(am|pm|a|p|h)?

Screen Shot 2014-04-01 at 9.36.50 PM

This one breaks each digit apart, which gives us more flexibility to work with the data in PHP. After getting the raw numbers I build a string and format it depending on length and composition. This way I can create a string that can reliably be interpreted by strtotime().

The real fun is using PHP to build a uniform time string from the pieces the regex makes for us. My code builds a string based on the length of input, and wether or not it has an AM / PM designation. ┬áIf the regex could not understand the entry, the PHP function returns a “fail” string. The bonus here is when you feed “fail” into strototime(), it returns a false (unlike “cat” which is a time!).

function parseTime($inTime) {
 $result; // Create the regex split array
 preg_match("/([0-9])([0-9])?:?([0-9])?([0-9])?[\s]?(am|pm|a|p|h)?/", $inTime, $result);
 $timeString = "";
 $timeString = $result[1] . $result[2] . $result[3] . $result[4];

 $length = strlen($timeString);
 $temp1 = substr($timeString,0,$length-2);
 $temp2 = substr($timeString,$length-2,$length);
if ($length > 2) {
 $timeString = $temp1 . ":" . $temp2;
}
if ($length == 1 || ($length == 2)) {
 $timeString = $timeString . ":00";
}
if ($result[5] == "a" || $result[5] == "am") {
 $timeString = $timeString . "am";
}
if ($result[5] == "p" || $result[5] == "pm") {
 $timeString = $timeString . "pm";
}
if ($length == 0) {
 $timeString = "fail";
}
 return $timeString;
}

Leave a Reply