Reputation: 55
So I want to check if my input field contains a specific characters and integers. The only value I accept is like this 'KM00000'. It must starts with KM and followed by 5 characters of integers.To check if the string starts with the letter 'KM', I can do this
if (substr($fm_id, 0, 2) !== "KM") {
die("<script>alert('ID is in the wrong format.');
window.history.back();</script>");
}
But I don't know how to check if the following characters after the letter "KM" is followed by an integer or not
Upvotes: 1
Views: 35
Reputation: 32232
function check_classic($input) {
if( strlen($input) !== 7 ) {
return false;
}
if( substr($input, 0, 2) !== 'KM' ) {
return false;
}
for( $i=0,$c=5,$s=substr($input, 2, 5); $i<$c; ++$i ) {
$ord = ord($s[$i]);
// ord('0') == 48, ord('9') == 57
if( $ord < 48 || $ord > 57 ) {
return false;
}
}
return true;
}
function check_regex($input) {
return preg_match('/^KM\d{5}$/', $input);
}
$inputs = [ 'KM12345', 'KM1234', 'KM123456', 'KM1234v' ];
foreach($inputs as $input) {
printf("Classic: %-8s %s\n", $input, check_classic($input) ? 'true' : 'false');
printf("Regex: %-8s %s\n", $input, check_regex($input) ? 'true' : 'false');
}
Output:
Classic: KM12345 true
Regex: KM12345 true
Classic: KM1234 false
Regex: KM1234 false
Classic: KM123456 false
Regex: KM123456 false
Classic: KM1234v false
Regex: KM1234v false
While the regular expression is certainly less lines of code, it's a different domain-specific language to learn. Plus I think it's important to show the "classic" approach to solving the problem as well, which is roughly what the regular expression is doing under the hood.
Ref:
Upvotes: 2