我使用preg_match来过滤通过提交按钮提供给我的电话号码。
我想接受以00
或+
开头的所有数字变体,然后是至少3个didgits。例如,00123
和+123
有效,12345
无效。这个数字可以是它想要的,并且最后包含许多资本A或F。我目前使用的版本似乎有点复杂,因为我试图想到我想拒绝的每个角色,而不是只允许我想要的那些。
//i check if the number starts with 00 or + and has atleast 3 didgtis following that
if(preg_match("/(^00|^\+)[0-9][0-9][0-9]+/", $nummer)){
//i then try to eliminate all characters i don't want which i can think of
if(preg_match("/([a-z]|[B-E]|[G-Z]|\s\.)/", $nummer)){
->deny}//actual code is different
else(preg_match("/([0-9]|A|F)/", $nummer)){
->allow}}//actual code is different
我知道我现在的preg_match并不关心我的A和F的位置,只要它们不在00
或+
之后的前三个位置之一,但我没有找到了解决这个问题的方法。
我想问的是,如果有一种方法可以拒绝除了你的比赛之外的所有输入,而不是允许一切,并且不得不考虑你不想要的一切。
我想让任何事情都没有通过测试,除非它看起来像这样:
00123456789123 or +123456789AAAAA or 00123FFFFFFFFFF or +123AAAAAAFFA
依旧......
答案 0 :(得分:0)
使用类似:
/^(+|00)\d{3,}[A-F]*$/
答案 1 :(得分:0)
这个完成工作:
^(?:00|\+)\d{3,}[AF]*$
<强>解释强>
^ : begining of line
(?: : start non capture group
00 : literally 00
| : OR
\+ : + sign
) : end group
\d{3,} : 3 or more digits
[AF]* : 0 or more letters A or F (change * to + if you want at least one letter)
$ : end of line
在行动中:
$tests = [
'00123456789123',
'+123456789AAAAA',
'00123FFFFFFFFFF',
'+123AAAAAAFFA',
'ABCD',
'123456F',
'00123B'
];
foreach($tests as $str) {
if(preg_match('/^(?:00|\+)\d{3,}[AF]*$/', $str)) {
echo "$str --> Match\n";
} else {
echo "$str --> NO match\n";
}
}
<强>输出:强>
00123456789123 --> Match
+123456789AAAAA --> Match
00123FFFFFFFFFF --> Match
+123AAAAAAFFA --> Match
ABCD --> NO match
123456F --> NO match
00123B --> NO match