[英]adding negative statement to regex
I am trying to check if a phone number like this exists in using regex. 我正在尝试检查使用正则表达式时是否存在这样的电话号码。
(001) 33992292
(001)33992292
So, I used 所以,我用过
if(preg_match("/[0-9\(\)]+/", $row)){
//is phone number
}
But, the problem with this is that, strings containing numbers get passed as well, like foo134@yahoo.com
, so how can I evaluate a phone number and exclude @
character is strings all together? 但是,问题在于,包含数字的字符串也会被传递,例如
foo134@yahoo.com
,那么如何评估电话号码并将@
字符排除在一起?
UDPATED /^(\\(\\d+\\))*\\s?(\\d+\\s*)+$/
UDPATED
/^(\\(\\d+\\))*\\s?(\\d+\\s*)+$/
you missed start string ^
sign and end string $
sign, what else your regex is wrong because 5545()4535 will also pass match 你错过了开始字符串
^
符号和结束字符串$
sign,还有你的正则表达式是错误的,因为5545()4535也会通过匹配
您需要在正则表达式中使用锚点 ,正确的语法是:
if(preg_match('~^\(\d{3}\) *\d{8}$~', $row)) { ... }
Telephone numbers are notorious for people to get wrong - and by people I mean programmers. 电话号码因人们出错而臭名昭着 - 人们指的是程序员。
For example, these are all "common" ways of writing a phone number: 例如,这些都是编写电话号码的“常见”方式:
(001) 33992292
001 33992292
00133992292
001 3399 2292
(001) 3399-2292
A saner approach it to just remove everything that isn't a number and check the length: 一个更安全的方法是删除所有不是数字的东西并检查长度:
$phonenumber = "(001) 33992292";
$phonenumber = preg_replace("/[^0-9,.]/", "", $phonenumber );
if (strlen($phonenumber) == 11) {
// do thing
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.