简体   繁体   中英

PHP: How to validate UK landline and mobile numbers?

How can I validate UK telephone numbers? I copied the answer from this site, but this answer only accept mobile number. I want to accept both landline and mobile number. Is it possible?

            # @reference: http://stackoverflow.com/questions/8099177/validating-uk-phone-numbers-in-php

            $telephone = "01752311149"; // not ok.
            $telephone = "07742055388"; // ok.
            $pattern = "/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/";

            if (!preg_match($pattern, $telephone))
            {
                $error = true;
                $message.='<error elementid="telephone" message="invalid" />';
            }

I have tried with this regex below but it doesn't work at all,

#http://stackoverflow.com/questions/14512810/regular-expression-mobile-and-landline-number
$pattern = "/^\(0\d{1,2}\)\d{3}-\d{4}$/";

There's a selection of regular expressions for validating phone numbers at Regular Expressions for Validating and Formatting GB Telephone Numbers :

Alternatively, there's one at RegExLib.com that seems to work well:

^((\(44\))( )?|(\(\+44\))( )?|(\+44)( )?|(44)( )?)?((0)|(\(0\)))?( )?(((1[0-9]{3})|(7[1-9]{1}[0-9]{2})|(20)( )?[7-8]{1})( )?([0-9]{3}[ -]?[0-9]{3})|(2[0-9]{2}( )?[0-9]{3}[ -]?[0-9]{4}))$

Edit:

This will allow mobile, landline, and special service numbers (999, 123, etc.) -- assumes that spaces have been stripped:

'/^(?>(?>\\+44|0)(?>(?!7624)(?>[12389]\\d|5[56]|7[06])\\d{8}|(?>(?>[58]00|1\\d{2})\\d{6})|(?>8001111|845464\\d)|7(?>[45789]\\d{8}|624\\d{6}))|999|112|100|101|111|116|123|155|118\\d{3}|(?>\\+44|0)(?>800111|8454647))$/D'

You'd be better off using an existing library, rather than trying your own validation, as rules are somewhat complex and likely to change with time.

For example, this PHP version of Google's libphonenumber :

$phoneUtil = PhoneNumberUtil::getInstance();
try {
    $numberProto = $phoneUtil->parse('02012345678', 'GB');
} catch (NumberParseException $e) {
    echo $e;
}

Then you can check the validity of the number with:

$phoneUtil->isValidNumber($numberProto);

Furthermore, this library allows you to detect the phone number type (fixed line, mobile, voip, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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