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 a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match a URL in a href attribute?
- How to use PHP regex to match an XML tag?
- How to use regex in PHP to match any digit?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a year?
- How to match a double quote in PHP regex?
- How to get last matched occurrence in PHP regex?
See more codes...