Php 荷兰电话号码的正则表达式

Php 荷兰电话号码的正则表达式,php,regex,Php,Regex,说到regex,我肯定不是最差的,但这件事让我很难堪 简而言之,这就是我目前拥有的代码 $aNumbers = array( '612345678', '546123465', '131234567', '+31(0)612345678' ); foreach($aNumbers as $sNumber) { $aMatches = array(); $sNumber = preg_replace('/(\(0\)|[^\d]+)/', '',

说到regex,我肯定不是最差的,但这件事让我很难堪

简而言之,这就是我目前拥有的代码

$aNumbers = array(
    '612345678',
    '546123465',
    '131234567',
    '+31(0)612345678'
);

foreach($aNumbers as $sNumber) {
    $aMatches = array();
    $sNumber = preg_replace('/(\(0\)|[^\d]+)/', '', $sNumber);

    preg_match('/(\d{1,2})?(\d{3})(\d{3})(\d{3})$/', $sNumber, $aMatches);

    var_dump($sNumber);
    var_dump($aMatches);
}
简单地说,我想匹配电话号码的特定格式,以确保统一显示

+31(0)612345678
+31(0)131234567
两者都将不带+和(0)。 分部分削减:

31     6    123 456 78
Country Net Number
31     13   123 456 78
Country Net Number
现在,在某些情况下,+31(或+1,+222)是可选的。6和13始终包括在内,但作为一种有趣的转变,以下格式也是可能的:

31     546  123 456
Country Net Number

这在正则表达式中可能吗?

我使用了nuget包libphonenumber csharp

这帮助我创建了一个(荷兰)电话号码验证器,这里是一个代码片段,没有我的解决方案的其他部分,它将不会编译,但至少您可以了解如何处理它

  public override void Validate()
    {
        ValidationMessages = new Dictionary<string, string>();
        ErrorMessage = string.Empty;
        string phoneNumber;
        string countryCode = _defaultCountryCode;

        // If the phoneNumber is not required, it is allowed to be empty.
        // So in that case isValid gets defaultvalue true
        bool isValid = (!_isRequired);

        if (!string.IsNullOrEmpty(_phoneNumber))
        {
            var phoneUtil = PhoneNumberUtil.GetInstance();
            try
            {
                phoneNumber = PhoneNumbers.PhoneNumberUtil.Normalize(_phoneNumber);
                countryCode = PhoneNumberUtil2.GetRegionCode(phoneNumber, _defaultCountryCode);
                PhoneNumber oPhoneNumber = phoneUtil.Parse(phoneNumber, countryCode);
                var t1 = oPhoneNumber.NationalNumber;
                var t2 = oPhoneNumber.CountryCode;
                var formattedNo = phoneUtil.Format(oPhoneNumber, PhoneNumberFormat.E164);
                isValid = PhoneNumbers.PhoneNumberUtil.IsViablePhoneNumber(formattedNo);
            }
            catch (NumberParseException e)
            {
                var err = e.ToString();
                isValid = false;
            }
        }

        if ((isValid) && (!string.IsNullOrEmpty(_phoneNumber)))
        {
            Regex regexValidator = null;
            string regex;

            // Additional validations for Dutch phone numbers as LibPhoneNumber is to graceful as it comes to
            // thinking if a number is valid.
            switch (countryCode)
            {
                case "NL":

                    if (_phoneNumber.StartsWith("0800") || _phoneNumber.StartsWith("0900"))
                    {
                        // 0800/0900 numbers
                        regex = @"((0800|0900)(-| )?[0-9]{4}([0-9]{3})?$)";
                        regexValidator = new Regex(regex);
                        isValid = regexValidator.IsMatch(_phoneNumber);
                    }
                    else
                    {
                        string phoneNumberCheck = _phoneNumber.Replace("(", "").Replace(")", "").Replace("-", "").Replace(" ", "");

                        regex = @"^(0031|\+31|0)[1-9][0-9]{8}$";

                        regexValidator = new Regex(regex);
                        isValid = regexValidator.IsMatch(phoneNumberCheck);
                    }
                    break;
            }
        }
        if (!isValid)
        {
            ErrorMessage = string.Format(TextProvider.Get(TextProviderConstants.ValMsg_IsInAnIncorrectFormat_0),
                ColumnInfoProvider.GetLabel(_labelKey));

            ValidationMessages.Add(_messageKey, ErrorMessage);
        }
    }
public override void Validate()
{
ValidationMessages=新字典();
ErrorMessage=string.Empty;
字符串电话号码;
字符串countryCode=\u defaultCountryCode;
//如果电话号码不是必需的,则允许为空。
//因此,在这种情况下,isValid将获取defaultvalue true
bool isValid=(!\u是必需的);
如果(!string.IsNullOrEmpty(_phoneNumber))
{
var phoneUtil=PhoneNumberUtil.GetInstance();
尝试
{
phoneNumber=phoneNumber.PhoneNumberTil.Normalize(\u phoneNumber);
countryCode=PhoneNumberTil2.GetRegionCode(电话号码,默认为countryCode);
PhoneNumber=phoneUtil.Parse(PhoneNumber,countryCode);
var t1=OphenNumber.NationalNumber;
var t2=oPhoneNumber.CountryCode;
var formattedNo=phoneUtil.Format(oPhoneNumber,PhoneNumberFormat.E164);
isValid=PhoneNumber.PhoneNumberUtil.IsViablePhoneNumber(格式化编号);
}
捕获(编号ParseException e)
{
var err=e.ToString();
isValid=false;
}
}
if((isValid)&(!string.IsNullOrEmpty(_phoneNumber)))
{
Regex regexValidator=null;
字符串正则表达式;
//荷兰电话号码作为LibPhoneNumber的附加验证是非常优雅的
//思考一个数字是否有效。
开关(国家代码)
{
案例“NL”:
如果(_phoneNumber.StartsWith(“0800”)||u phoneNumber.StartsWith(“0900”))
{
//0800/0900号
正则表达式=@“((0800 | 0900)(-)?[0-9]{4}([0-9]{3})?$)”;
regexValidator=新的Regex(Regex);
isValid=regexValidator.IsMatch(\u phoneNumber);
}
其他的
{
字符串phoneNumber检查=_phoneNumber.Replace(“,”).Replace(“),”).Replace(“-”,”).Replace(“,”);
正则表达式=“^(0031 | \+31 | 0)[1-9][0-9]{8}$”;
regexValidator=新的Regex(Regex);
isValid=regexValidator.IsMatch(phoneNumberCheck);
}
打破
}
}
如果(!isValid)
{
ErrorMessage=string.Format(TextProvider.Get(TextProviderConstants.ValMsg_IsInAnIncorrectFormat_0),
ColumnInfoProvider.GetLabel(_labelKey));
添加(_messageKey,ErrorMessage);
}
}
同样有用的还有我的类PhoneNumberTil2,它构建在nuget包libphonenumber csharp上:

// Code start
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using PhoneNumbers;

namespace ProjectName.Logic.Miscellaneous
{
    public class PhoneNumberUtil2
    {
        /// <summary>
        /// Returns the alphanumeric country code for a normalized phonenumber. If a phonenumber does not contain 
        /// an international numeric country code, the default country code for the website is returned.
        /// This works for 17 countries: NL, GB, FR, DE, BE, AU, SE, NO, IT, TK, RU, CH, DK, IR, PT, ES, FI
        /// </summary>
        /// <param name="normalizedPhoneNumber"></param>
        /// <param name="defaultCountryCode"> </param>
        /// <returns></returns>
        public static string GetRegionCode(string normalizedPhoneNumber, string defaultCountryCode)
        {
            if (normalizedPhoneNumber.Length > 10)
            {
                var dict = new Dictionary<string, string>();
                dict.Add("7", "RU");
                dict.Add("43", "AT");
                dict.Add("32", "BE");
                dict.Add("45", "DK");
                dict.Add("33", "FR");
                dict.Add("49", "DE");
                dict.Add("39", "IT");
                dict.Add("31", "NL");
                dict.Add("47", "NO");
                dict.Add("34", "ES");
                dict.Add("46", "SE");
                dict.Add("41", "CH");
                dict.Add("90", "TR");
                dict.Add("44", "GB");
                dict.Add("351", "PT");
                dict.Add("353", "IE");
                dict.Add("358", "FI");

                // First check 3-digits International Calling Codes
                if (dict.ContainsKey(normalizedPhoneNumber.Substring(0, 3)))
                {
                    return dict[normalizedPhoneNumber.Substring(0, 3)];
                }

                // Then 2-digits International Calling Codes 
                if (dict.ContainsKey(normalizedPhoneNumber.Substring(0, 2)))
                {
                    return dict[normalizedPhoneNumber.Substring(0, 2)];
                }

                // And finally 1-digit International Calling Codes
                if (dict.ContainsKey(normalizedPhoneNumber.Substring(0, 1)))
                {
                    return dict[normalizedPhoneNumber.Substring(0, 1)];
                }
            }
            return defaultCountryCode;
        }

    }
}
//代码开始
使用System.Collections.Generic;
利用制度全球化;
使用System.Linq;
使用系统文本;
使用电话号码;
命名空间ProjectName.Logic.Miscellaneous
{
公共类电话号码Til2
{
/// 
///返回标准化电话号码的字母数字国家代码。如果电话号码不包含
///国际数字国家代码,返回网站的默认国家代码。
///这适用于17个国家:NL、GB、FR、DE、BE、AU、SE、NO、IT、TK、RU、CH、DK、IR、PT、ES、FI
/// 
/// 
///  
/// 
公共静态字符串GetRegionCode(字符串normalizedPhoneNumber,字符串defaultCountryCode)
{
如果(normalizedPhoneNumber.Length>10)
{
var dict=新字典();
添加(“7”、“RU”);
添加(“43”,“AT”);
添加(“32”,“BE”);
第45条(“DK”);
第33条(“FR”);
添加(“49”,“DE”);
添加(“39”、“它”);
添加(“31”,“NL”);
添加(“47”、“否”);
添加(“34”、“ES”);
添加(“46”,“SE”);
第41条(“CH”);
添加(“90”,“TR”);
添加(“44”,“GB”);
添加(“351”、“PT”);
添加(“353”、“IE”);
添加(“358”、“FI”);
//首先检查3位国际电话号码
if(dict.ContainsKey(normalizedPhoneNumber.Substring(0,3)))
{
返回dict[normalizedPhoneNumber.Substring(0,3)];
}
//然后是两位数的国际呼叫码
if(dict.ContainsKey(normalizedPhoneNumber.Substring(0,2)))
{
返回dict[normalizedPhoneNumber.Substring(0,2)];
}
//最后是1位数的国际呼叫码
if(dict.ContainsKey(normalizedPhoneNumber.Substring(0,1)))
{
返回dict[normalizedPhoneNumber.Substring(0,1)];
}
}
返回默认国家代码;
}
}
}
我有一个
^[ -]*(\+31)?[ -]*[(0)]*[ -]*(7|43|32|45|33|49|39|31|47|34|46|41|90|44|351|353|358)[ -]*((?:\d[ -]*)+)
^[ -]*(\+31)?[ -]*[(0)]*[ -]*([123457]0|23|24|26|35|45|71|73|570)[ -]*((?:\d[ -]*)+)
input                     (1)    (2)    (3) 
---------------------    ------ ------ ---------------
0707123456                       70     7123456
0267-123456                      26     7-123456
0407-12 34 56                    40     7-12 34 56
0570123456                       570    123456
07312345                         73     12345
+31(0)734423211           +31    73     4423211 
10|111|113|114|115|117|118|13|15|161|162|164|165|166|167|168|172|174|180|181|182|183|184|186|187|20|222|223|224|226|227|228|229|23|24|251|252|255|26|294|297|299|30|313|314|315|316|317|318|320|321|33|341|342|343|344|345|346|347|348|35|36|38|40|411|412|413|416|418|43|45|46|475|478|481|485|486|487|488|492|493|495|497|499|50|511|512|513|514|515|516|517|518|519|521|522|523|524|525|527|528|529|53|541|543|544|545|546|547|548|55|561|562|566|570|571|572|573|575|577|578|58|591|592|593|594|595|596|597|598|599|70|71|72|73|74|75|76|77|78|79
1([035]|1[134578]|6[124-8]|7[24]|8[0-467])|2([0346]|2[2346-9]|5[125]|9[479])|3([03568]|1[34-8]|2[01]|4[1-8])|4([0356]|1[12368]|7[58]|8[15-8]|9[23579])|5([0358]|[19][1-9]|2[1-5789]|4[13-8]|6[126]|7[0-3578])|7[0-9]