4

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

Adarsh Madrecha
  • 6,364
  • 11
  • 69
  • 117

4 Answers4

7

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
5

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

1
$mob = "9513574562";
if(preg_match("/^\d+\.?\d*$/",$mob) && strlen($mob)==10){

echo 1;

}else{

 echo 0;

}

preg_match() checking it is integer or not and in strlen() it is checking no of digit in this string. If 2 condition satisfy then it is a 10 digit valid mobile no

Milan Krushna
  • 317
  • 2
  • 5
0

for pakistani mobile number the regex code will be the following

^[9][2][3][0-9]{9}$
Hassan Qasim
  • 463
  • 5
  • 5