Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match for validating 10 digit mobile number

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

like image 437
Adarsh Madrecha Avatar asked Dec 11 '22 09:12

Adarsh Madrecha


2 Answers

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.

like image 189
Tim Biegeleisen Avatar answered Dec 28 '22 08:12

Tim Biegeleisen


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

like image 26
Sudheesh S Babu Avatar answered Dec 28 '22 07:12

Sudheesh S Babu