php-regexHow to use PHP regex to match time?
PHP regex can be used to match time by using the preg_match()
function. This function takes two parameters, the first being the regular expression pattern and the second being the string to match against.
$pattern = '/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/';
$string = '12:30';
if (preg_match($pattern, $string)) {
echo 'Time matched!';
}
Output example
Time matched!
Code explanation
$pattern
: This is the regular expression pattern used to match the time. It matches any time in the 24-hour format (e.g. 12:30).$string
: This is the string to match against.preg_match()
: This is the function used to match the regular expression pattern against the string. It returnstrue
if the pattern matches, andfalse
otherwise.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a multiline?
- How to match a quotation mark in PHP regex?
- How to get last matched occurrence in PHP regex?
- How to match a single quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a year?
- How to match a space using PHP regex?
See more codes...