PHP 中的手机号码验证模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35892543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mobile number validation pattern in PHP
提问by sanzuu
I am unable to write the exact pattern for 10 digit mobile number (as 1234567890 format) in PHP . email validation is working.
我无法在 PHP 中为 10 位手机号码(如 1234567890 格式)编写确切的模式。电子邮件验证正在工作。
here is the code:
这是代码:
function validate_email($email)
{
return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,6}$", $email);
}
function validate_mobile($mobile)
{
return eregi("/^[0-9]*$/", $mobile);
}
回答by Panda
Mobile Number Validation
手机号码验证
You can preg_match()
to validate 10-digit mobile numbers:
您可以preg_match()
验证 10 位手机号码:
preg_match('/^[0-9]{10}+$/', $mobile)
To call it in a function:
在函数中调用它:
function validate_mobile($mobile)
{
return preg_match('/^[0-9]{10}+$/', $mobile);
}
Email Validation
电子邮件验证
You can use filter_var()
with FILTER_VALIDATE_EMAIL
to validate emails:
您可以使用filter_var()
withFILTER_VALIDATE_EMAIL
来验证电子邮件:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
To call it in a function:
在函数中调用它:
function validate_email($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
However, filter_var
will return filtered value on success and false
on failure.
但是,filter_var
将在成功和false
失败时返回过滤值。
More information at http://www.w3schools.com/php/php_form_url_email.asp.
更多信息请访问http://www.w3schools.com/php/php_form_url_email.asp。
Alternatively, you can also use preg_match()
for email, the pattern is below:
或者,您也可以preg_match()
用于电子邮件,模式如下:
preg_match('/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', $email)
回答by Rafael Xavier
You can use this regex below to validate a mobile phone number.
您可以使用下面的这个正则表达式来验证手机号码。
\+ Require a + (plus signal) before the number
[0-9]{2} is requiring two numeric digits before the next
[0-9]{10} ten digits at the end.
/s Ignores whitespace and break rows.
$pattern = '/\+[0-9]{2}+[0-9]{10}/s';
OR for you it could be:
$pattern = '/[0-9]{10}/s';
If your input text won't have break rows or whitespaces you can simply remove the 's' at the end of our regex, and it will be like this:
$pattern = '/[0-9]{10}/';