3

I'm definitely not the worst when it comes down to regex, but this one has got me stumped.

In short, this is the code I currently have.

$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);
}

Simply put, I want to match specific formats for telephone numbers to ensure a unified display.

+31(0)612345678
+31(0)131234567

Both stripped would be without + and (0). Cut down in parts:

31     6    123 456 78
Country Net Number
31     13   123 456 78
Country Net Number

Now, in some cases the +31 (or +1, +222) are optional. The 6 and 13 are always included, but as a fun twist, the following format is also possible:

31     546  123 456
Country Net Number

Is this even possible with regex?

4
  • stackoverflow.com/a/17949938/3166303
    – leeor
    Oct 14, 2015 at 12:12
  • yes but not if we don't now all the Net numbers.
    – Kanti
    Oct 14, 2015 at 12:13
  • 1
    Are you sure you have the 8 at the end of your 2nd example ? This does not seem to match the number you wrote before cutting it down in part.
    – Mathiou
    Oct 14, 2015 at 12:19
  • Where does the data come from? Ideally you shouldn't have to do this. When users fill in a form the calling code and phone number should be in their own separate fields, and all you should have to do is sanitize it. Oct 14, 2015 at 12:48

2 Answers 2

1

I've answered a few of these types of questions, and my strategy is to identify certain portions of formatting or number relationships that convey meaning, and get rid of the rest.

One of my examples that parses non-NANP number formatting uses a list of valid area codes in the parsing expression, and identifies country code when present. It extracts the country code, area code, and then the rest of the number.

or your country, I am assuming the list of area/net/region codes in HansM's answer is either correct or easily replaceable, so I'll guess that this modification of a regex might be useful:

^[ -]*(\+31)?[ -]*[(0)]*[ -]*(7|43|32|45|33|49|39|31|47|34|46|41|90|44|351|353|358)[ -]*((?:\d[ -]*)+)

It will first match the country code, if it is present, and store it in back-reference 1, then ignore a single zero. It will then match one of the area/net/region codes and store it in back-reference 2. It will then get any number of digits (one or more), mixed with dashes (-) and/or spaces () and store those into back-reference 3

After this, you could parse the third numbering group for validity or further reformatting

I'm testing it on Regex 101, but I could use a list of acceptable and unacceptable input, and how it should be reformatted when acceptable...

[EDIT]

I've used this list of city codes for the Netherlands and modified the expression thusly:

^[ -]*(\+31)?[ -]*[(0)]*[ -]*([123457]0|23|24|26|35|45|71|73|570)[ -]*((?:\d[ -]*)+)

which performs the following parsing:

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 

but I still don't know if that's helpful for you

[EDIT 2]

Wikipedia has what appears to be a more comprehensive list of codes

010, 0111, 0113, 0114, 0115, 0117, 0118, 013, 015, 0161, 0162, 0164, 0165, 0166, 0167, 0168, 0172, 0174, 0180, 0181, 0182, 0183, 0184, 0186, 0187, 020, 0222, 0223, 0224, 0226, 0227, 0228, 0229, 023, 024, 0251, 0252, 0255, 026, 0294, 0297, 0299, 030, 0313, 0314, 0315, 0316, 0317, 0318, 0320, 0321, 033, 0341, 0342, 0343, 0344, 0345, 0346, 0347, 0348, 035, 036, 038, 040, 0411, 0412, 0413, 0416, 0418, 043, 045, 046, 0475, 0478, 0481, 0485, 0486, 0487, 0488, 0492, 0493, 0495, 0497, 0499, 050, 0511, 0512, 0513, 0514, 0515, 0516, 0517, 0518, 0519, 0521, 0522, 0523, 0524, 0525, 0527, 0528, 0529, 053, 0541, 0543, 0544, 0545, 0546, 0547, 0548, 055, 0561, 0562, 0566, 0570, 0571, 0572, 0573, 0575, 0577, 0578, 058, 0591, 0592, 0593, 0594, 0595, 0596, 0597, 0598, 0599, 070, 071, 072, 073, 074, 075, 076, 077, 078, 079

which can be used in the code selection portion like this (if you'd prefer it to be more easily read and updated):

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

or like this (if you'd prefer a more efficient evaluation of the expression):

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]
2
  • I'm gonna try to incorporate this tomorrow when I'm back at work but your solution seems like a decent only. I'll rated it answered it it works, thanks!
    – ReSpawN
    Oct 15, 2015 at 17:11
  • @ReSpawN -- sounds good - if you need help reformatting the rest of the number, I can try to help with that as well Oct 15, 2015 at 17:35
0

I have used the nuget package libphonenumber-csharp.

That has helped me to create a (Dutch) phone number validator, here is a code snippet, without other parts of my solution it will not compile but at least you can get an idea of how to handle this.

  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);
        }
    }

Also useful might be my class PhoneNumberUtil2 that builds upon the nuget package 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;
        }

    }
}
4
  • 1
    While OP is not looking for a .NET solution, drilling into the library might give you the right regex for this question...
    – tofutim
    Oct 14, 2015 at 12:49
  • You might be right, sorry for that. But indeed the switch statement with the different regex expressions might still be useful.
    – HansM
    Oct 14, 2015 at 13:31
  • While I can't fluently type .NET I can still read it like any other programmer out there - the logic is fine. Unfortunately not really what I need, but thanks anyways!
    – ReSpawN
    Oct 15, 2015 at 17:10
  • Sorry I couldn't help you but bottom line I could not solve it using one RegEx, but needed two regular expressions in a switch statement and some pre-validation and formatting before checking the number with the regular expressions. Maybe you can follow similar logic in your code.
    – HansM
    Oct 15, 2015 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.