jma*_*ate 28
以下是我找到有效的10位美国电话号码的方法.此时我假设用户想要我的内容,因此数字本身是可信的.我正在使用最终发送短信的应用程序,所以我只想要原始数字,无论如何.格式化总是可以在以后添加
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Run Code Online (Sandbox Code Playgroud)
编辑:如果有人感兴趣,我最终不得不将其移植到Java.它运行在每次按键上,所以我试着保持它相当轻:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
Run Code Online (Sandbox Code Playgroud)
Ben*_*owe 25
由于电话号码必须符合模式,因此您可以使用正则表达式将输入的电话号码与您在regexp中定义的模式相匹配.
php同时具有ereg和preg_match()函数.我建议使用preg_match(),因为这种正则表达式的文档更多.
一个例子
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
Run Code Online (Sandbox Code Playgroud)