View Full Version : validate time format using ereg()
kramx7
12-13-2006, 04:52 AM
I want to check the input from the user if its is a correct time format.
The user must enter the time in a 12 hour format (hh:mm AM/PM)
I used the ereg function but it will not work.
I Hope someone will help me.
My code is written below.
if(ereg("([0-9]{1,2})|:|([0-9]{1,2})| |([AMPM]{2})", $info['time']))
{
// ok
}else{
// error
}
thanks.
wordnerd
12-13-2006, 09:52 PM
I want to check the input from the user if its is a correct time format.
The user must enter the time in a 12 hour format (hh:mm AM/PM)
I used the ereg function but it will not work.
I Hope someone will help me.
My code is written below.
if(ereg("([0-9]{1,2})|:|([0-9]{1,2})| |([AMPM]{2})", $info['time']))
{
// ok
}else{
// error
}
thanks.
This is the regex I use for 12-hour am/AM/PM/pm checking. Give it a whirl
if (ereg('(^([0-9]|[0-1][0-9]|[2][0-3]):([0-5][0-9])(\s{0,1})([AM|PM|am|pm]{2,2})$)|(^([0-9]|[1][0-9]|[2][0-3])(\s{0,1})([AM|PM|am|pm]{2,2})$)',$string)) {
//good
} else {
//error
}
Hope that helps you out.
ralph l mayo
12-14-2006, 12:22 AM
Sorry, preg_match, but they're faster/better:
# Returns time in HH:MM[AM|PM] format if it matches, else false
function canonicalize_time($time)
{
return (preg_match('/[\s0]*(\d|1[0-2]):(\d{2})\s*([AaPp][Mm])/xms', $time, $match))
? sprintf('%02d:%d%s', $match[1], $match[2], strtoupper($match[3]))
: false;
}
Depending on your circumstance and how important it is that the server be exactly clear on what time is meant this might not be advisable, but you can also do something like:
echo date('g:iA', strtotime($time));
where $time can be 12 hour, 24 hour, or even things like 'noon' or '30 minutes ago'
kramx7
12-14-2006, 02:57 AM
Thank you guys.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.