使用 PHP 进行正则表达式电话号码验证 [英] regex phone number validation with PHP
问题描述
这是关于我之前问过的一个问题的另一个问题 昨天.我希望允许用户按以下格式键入美国电话号码.
This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.
(800)-555-1212
(800)-555-1212
800-555-1212
800-555-1212
让它只检查数据库中的数字 8005551212
and have it only check the database for numbers 8005551212
我见过这样的正则表达式<代码>/^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/
I've seen that regex like
/^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/
可能有效,但我不确定如何从我提供的链接将其实现到代码中
may work but I'm not certain how to implement it into the code from the link I provided
我是 php 新手,对正则表达式一无所知.任何帮助表示赞赏.
I'm new to php and know nothing about regex. Any help is appreciated.
推荐答案
该函数验证一个电话号码,如果通过则返回true,如果无效则返回false.这个函数非常简单,我被写入了.
This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.
/**
* @param $number
*
* @return bool
*/
function validatePhoneNumber($number) {
$formats = [
'###-###-####', '####-###-###',
'(###) ###-###', '####-####-####',
'##-###-####-####', '####-####', '###-###-###',
'#####-###-###', '##########', '#########',
'# ### #####', '#-### #####'
];
return in_array(
trim(preg_replace('/[0-9]/', '#', $number)),
$formats
);
}
这篇关于使用 PHP 进行正则表达式电话号码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!