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 returnstrueif the pattern matches, andfalseotherwise.
Helpful links
More of Php Regex
- How to use PHP regex to match whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex with zero or more occurrences?
- How to match a single quote in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match URL?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match URL path?
See more codes...