简体   繁体   English

验证新西兰电话号码的正则表达式

[英]Regular expression to validate New Zealand phone numbers

I need a regular expression that works in PHP and JavaScript to validate New Zealand local, mobile and freecall (0800) phone numbers.我需要一个适用于 PHP 和 JavaScript 的正则表达式来验证新西兰本地、移动和免费电话 (0800) 电话号码。

Matches:     (09)1234567, (021)123456, (021)1234567, (027)123456, 0800 12345, 0800 1234578
Non-Matches: (09)123456 , (021)12345 , (031)1234567, (027)12345 , 0800-1234, 0800123456789

Below is a regular expression I found on the web but it does not seem to work for some reason:下面是我在 web 上找到的一个正则表达式,但由于某种原因它似乎不起作用:

(^([0]\d{1}))(\d{7}$)|(^([0][2]\d{1}))(\d{6,8}$)|([0][8][0][0])([\s])(\d{5,8}$) (^([0]\d{1}))(\d{7}$)|(^([0][2]\d{1}))(\d{6,8}$)|( [0][8][0][0])([\s])(\d{5,8}$)

Can someone please help with the expression above?有人可以帮忙解决上面的表达吗? Thank you for your help in advance.提前谢谢你的帮助。

UPDATE - I worked it out and the solution is below:更新 - 我已经解决了,解决方案如下:

$phone_number = preg_replace('/[^\d\(\)]/', '', $phone_number);
$pattern = '/^(\((03|04|06|07|09)\)\d{7})|(\((021|022|025|027|028|029)\)\d{6,8})|((0508|0800|0900)\d{5,8})$/';

Why all those parentheses and brackets? 为什么所有这些括号和括号?

^(\(0\d\)\d{7}|\(02\d\)\d{6,8}|0800\s\d{5,8})$

You dont have to wrap everything in pair of parentheses to make it work. 你不必用括号括起所有东西来使它工作。 That's voodoo programming. 这是伏都教编程。 For example, ([0][8][0][0]) is simply 0800 . 例如, ([0][8][0][0])仅为0800

There's not enough information about the formatting of NZ phone numbers in your question to be sure about this, but a trick may be to first remove all non digit characters and after that test for the number of digits (as far as I can see it should be 9 digits?). 在你的问题中没有足够的关于NZ电话号码格式的信息以确定这一点,但一个技巧可能是首先删除所有非数字字符,然后在测试后检查数字位数(据我所知,它应该是9位?)。 Something like: 就像是:

var phonenr = '(09)1234567'.replace(/[\(\)\s\-]/g,'')
   ,valid   = phonenr.length === 9;
// or check if it's all digits, starting with 0 as well as the length
valid = /^0\d+$/.test(phonenr) && phonenr.length === 9

The answer is outdated, 020 is a valid mobile phone prefix now.答案已过时,020 现在是有效的手机前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM