I am trying to validate 10 digits mobile number using PHP function preg_match. The below code does not produce any output.
Is it the regex wrong? or I am using it incorrectly.
I was expecting Hi True
in the output. if it matches or Hi False
if it does not match.
<?php
$value = '9987199871';
$mobileregex = "/^[1-9][0-9]{10}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1; // @debug
?>
regex taken from https://stackoverflow.com/a/7649835/4050261
The regex you stated will match eleven digits, not ten. Since all Indian mobile numbers start with 9,8,7, or 6, we can use the following regex:
^[6-9][0-9]{9}$
Here is your code snippet updated:
$value = '9987199871';
$mobileregex = "/^[6-9][0-9]{9}$/" ;
echo "Hi " . preg_match($mobileregex, $value) === 1;
Note that the above regex is still probably far from the best we could do in terms of validation, but it is at least a start.
The following code snippet will check if the mobile number digits are within 10-15 digits including '+' at the start and followed by a non-zero first digit.
Regular expression
"/^[+]?[1-9][0-9]{9,14}$/"
Code snippet
// Validation for the mobile field.
function validateMobileNumber($mobile) {
if (!empty($mobile)) {
$isMobileNmberValid = TRUE;
$mobileDigitsLength = strlen($mobile);
if ($mobileDigitsLength < 10 || $mobileDigitsLength > 15) {
$isMobileNmberValid = FALSE;
} else {
if (!preg_match("/^[+]?[1-9][0-9]{9,14}$/", $mobile)) {
$isMobileNmberValid = FALSE;
}
}
return $isMobileNmberValid;
} else {
return false;
}
}
^ symbol of the regular expression denotes the start
[+]? ensures that a single(or zero) + symbol is allowed at the start
[1-9] make sure that the first digit will be a non zero number
[0-9]{9,14} will make sure that there is 9 to 14 digits
$ denotes the end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With