How to match a time pattern like 2h30m with preg_match
This expression can be used when you want to validate a pattern containing houres and minutes or just hours or just minutes. The time pattern to accept is:
[some digits]h[some digits]m like:
22H34m is OK
2H34m is OK
2H3m is OK
202H340m is OK
x22H34m3 is NOT OK
22x34m3 is NOT OK
22H34mc is NOT OK
22h is OK
5m is OK
45hm is NOT OK
34m4h is NOT OK
hm is NOT OK
<?php
$test[] = "22H34m";
$test[] = "2H34m";
$test[] = "2H3m";
$test[] = "202H340m";
$test[] = "x22H34m3";
$test[] = "22x34m3";
$test[] = "22H34mc";
$test[] = "22h";
$test[] = "45m";
$test[] = "45hm";
$test[] = "34m4h";
$test[] = "hm";
foreach ($test as $key => $value) {
if (preg_match('/(^[0-9]{1,}h[0-9]{1,}m$)|(^[0-9]{1,}h$)|(^[0-9]{1,}m$)/i', $value)) {
echo "<br>".$value . " is OK";
} else {
echo "<br>".$value . " is NOT OK";
}
}
//This '|(^\d+$)' will even allow numeric values
preg_match('/(^[0-9]{1,}h[0-9]{1,}m$)|(^[0-9]{1,}h$)|(^[0-9]{1,}m$)|(^\d+$)/i', $value)
?> Knowledge keywords:
