简体   繁体   English

验证php中的电话号码

[英]Validate phone number in php

I am making a phone number validator and all numbers should start with 168 and then followed by 9 digits 123456789 .In total the phone number should only have 12 digits. 我正在做一个电话号码验证器,所有电话号码应以168开头,然后是9位数字123456789总的来说,电话号码只能包含12位数字。

I have tried this 我已经试过了

$phoneNumber = '168921500789';
    if( preg_match( "/^\168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}

When i run the script,the number is not valid.How can i make the script take only 12 digits that must start with 168?. 运行脚本时,该数字无效。如何使脚本仅使用必须以168开头的12位数字?

Your RegEx is wrong, there's an useless backslash before the 1 . 您的RegEx错误,在1之前有一个无用的反斜杠。 Correct: 正确:

/^168[0-9]{9}$/

Full code: 完整代码:

$phoneNumber = '168921500789';
if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}

You had to remove 1 slash: 您必须删除1个斜杠:

$phoneNumber = '168921500789';
    if( preg_match( "/^168[0-9]{9}$/", $phoneNumber ) ){
  echo "Valid number";
} else {
  echo "Invalid number";
}

we using like this, with referred this link 我们这样使用,并引用此链接

public function validatePhoneNumber($number){
 $formats = array(
    '###-###-####', '####-###-###',
    '(###) ###-###','####-####-####',
    '##-###-####-####','####-####','###-###-###',
    '#####-###-###', '##########', '#########',
    '# ### #####', '#-### #####'
 );

 $format = trim(preg_replace('/[0-9]/', '#', $number));
 return (in_array($format, $formats)) ? true : false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM