我使用preg_match来过滤通过提交按钮给我的电话号码。我想接受以下数字的所有变体:00
或+
,其次是至少3个DIDGIT。例如,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
等...
这个工作:
^(?: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 --> Matchn";
} else {
echo "$str --> NO matchn";
}
}
输出:
00123456789123 --> Match
+123456789AAAAA --> Match
00123FFFFFFFFFF --> Match
+123AAAAAAFFA --> Match
ABCD --> NO match
123456F --> NO match
00123B --> NO match
使用类似:
/^(+|00)d{3,}[A-F]*$/