12-Hour Time (H:MM AM/PM) Regex for PHP
/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching 12-hour time (h:mm am/pm), ported and verified for PHP. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// 12-Hour Time (H:MM AM/PM)
// ReDoS-safe | RegexVault — Localization > Time Formats
define('12HOUR_TIME_HMM_AMPM_PATTERN', '/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/');
function validate_12hour_time_hmm_ampm(string $input): bool {
return (bool) preg_match(12HOUR_TIME_HMM_AMPM_PATTERN, $input);
}
// Example
var_dump(validate_12hour_time_hmm_ampm("12:30 PM")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
12:30 PM | 13:00 PM |
1:05 AM | 0:30 AM |
11:59:59 PM | 12:60 PM |
12:00 AM | 12:30 |
9:30am | 12:30 pm extra |
12:00PM | — |
When to use this pattern
This pattern is drawn from the Localization > Time Formats category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
12:00 AM (midnight) and 12:00 PM (noon) confuse even native English speakers. Consider rejecting 12-hour format for any time-critical input and requiring 24-hour instead.
Technical Notes
12:00 AM = midnight, 12:00 PM = noon — the most commonly confused values. 12-hour format is standard in US, UK, Australia, and parts of Asia. Many others use 24-hour exclusively.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern