Skip to content
Advertisement

Validating UK phone numbers in PHP

I purchased a contact form. Great little thing but I need to convert the validation for the phone number to allow for UK number formats – in other words, to allow for spaces.

Right now it validates without spaces and has a minimum length of 8 characters:

if(is_numeric($phone))
{
    if(!$phone || strlen($phone) < 8)
    {
        $error .= "Please enter your phone number without spaces.<br />";
    }
}
else
{
    $error .= "Please enter numeric characters in the phone number field.<br />";
}

Advertisement

Answer

Phone numbers are typically horrible for regex patterns, which is what you will need.

This pattern for example:

$pattern = "/^(+44s?7d{3}|(?07d{3})?)s?d{3}s?d{3}$/";

$match = preg_match($pattern,$input);

if ($match != false) {
    // We have a valid phone number
} else {
    // We have an invalid phone number
}

That pattern will match with +44 included or not e.g.

all these will match:

07222 555555

(07222) 555555

+44 7222 555 555

These won’t

7222 555555

+44 07222 555555

(+447222) 555555

There are a load of sites that offer tutorials / cheat sheets etc. for regular expressions try some of these:

http://regexlib.com/Default.aspx

as well as a very good stack overflow post:

A comprehensive regex for phone number validation

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement