如何在正则表达式中匹配多个电话号码长度和格式?
^(?:080|070|081|\+?234)(?!.*-.*-)(?:\d(?:-)?){(8|10)}$
这是我的代码:
if (!preg_match("^(?:080|070|081|\+?234)(?!.*-.*-)(?:\d(?:-)?){(8)}$", $mobile)) {
// valid mobile number
}
我想支持以下数字格式:
+2347036756899
+234-7036-756899
07036756899
08036756899
使用此模式:
^(?:0|\+234)-?(?:80|70|81)-?\d{2}-?\d{6}$
(?:0|\+234)
您的国家/地区代码或零-?
可选破折号(?:80|70|81)
您的有效前缀\d{2}
续2位数字-?
再次可选破折号\d{6}
最后 6 个数字图案解释:
^ #match start of string
(?: #non-capturing group
\+234(-)? #match literal +, then 234, then an optional hyphen <-|
| #OR |
0 #match 0 |
) #end non-capturing group |
(?:[78]0|81) #match 70, 80, or 81 |
\d{2} #match two digits |
(?(1)-|) #conditionally require hyphen if hyphen after 234 ->|
\d{6} #match 6 digits
$ #match end of string
代码:(演示)
$tests = [
'+2347036756899',
'+234-7036-756899',
'+2347036-756899',
'+234-7036756899',
'07036756899',
'0-7036756899',
'07036-756899',
'08036756899',
];
foreach ($tests as $test) {
printf(
"%20s : %s\n",
$test,
preg_match('/^(?:\+234(-)?|0)(?:[78]0|81)\d{2}(?(1)-|)\d{6}$/', $test) ? '✅' : '❌'
);
}
输出:
+2347036756899 : ✅
+234-7036-756899 : ✅
+2347036-756899 : ❌
+234-7036756899 : ❌
07036756899 : ✅
0-7036756899 : ❌
07036-756899 : ❌
08036756899 : ✅