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 match a space using PHP regex?
- How to use PHP regex to match a zip code?
- 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 with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match URL path?
- How to use named capture groups in PHP regex?
- How to use PHP regex to match special characters?
See more codes...