Zoolander
Zoolander

Reputation: 2363

How to update this PHP regex to not allow more than 10 digits in a phone number?

I'm using the following regex to ensure a valid phone number is entered. It currently does not flag an error if more than 10 digits are entered.

How can this be fixed?

public function phoneNumber($value) {
    if (preg_match("/^\(?[0-9]{3}\)? *-? *[0-9]{3} *-? *[0-9]{4}$/", $value)) {
        return true;
    }

    return false;
}

Here's a test case that is currently showing up as a valid phone number, when it shouldn't:

35353535355535555555

Upvotes: 1

Views: 1562

Answers (2)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

It's not a good idea to filter out foreign numbers or numbers with extensions. Here's an example that I use for converting common numbers for a specific format for CRM injection. Includes spam scoring.

<?php
    function phoneNumber($value) {
        $phoneScore = 0;
        $numbers = preg_replace('![^0-9]!','',$value);
        //if it's too small to be a US number, then ramp it up.
        if (!empty($value)&&(strlen($numbers) < 10)){
            $phoneScore = $phoneScore + 3;
        } elseif (empty($value)){
            $phoneScore = $phoneScore + 10;     
        }
        return $phoneScore;
    }

    $numbers = array(
    '(911 -535 -3535',
    '800.555.1212',
    '800  458 2180',
    '800 - 458 2180',
    '800 - 458-2180',
    '',
    '800-555-1212 ext# 212',
    '+49 (0)69 974640',
    '+86 (021) 5466-2808',
    '+66 (02) 261-3525',
    '+44 (020) 7626-0224',
    '123456',
    );

    $patterns = array('![^0-9xX#+]!','!-+!','!-?[xX#]-?!','!#+!','!#!','!^-!');
    $replacements = array("-","-",'#','#',' #','');

    foreach ($numbers as $value){
        $score = phoneNumber($value);
        $clean_num = preg_replace($patterns,$replacements,$value);
        echo "$value = Score $score.<br />\n Cleaned Number = $clean_num<br />\n<br />\n";
    }

?>

Output looks like this:

(911 -535 -3535 = Score 0. Cleaned Number = 911-535-3535

800.555.1212 = Score 0. Cleaned Number = 800-555-1212

800 458 2180 = Score 0. Cleaned Number = 800-458-2180

800 - 458 2180 = Score 0. Cleaned Number = 800-458-2180

800 - 458-2180 = Score 0. Cleaned Number = 800-458-2180

= Score 10. Cleaned Number =

800-555-1212 ext# 212 = Score 0. Cleaned Number = 800-555-1212 #212

+49 (0)69 974640 = Score 0. Cleaned Number = +49-0-69-974640

+86 (021) 5466-2808 = Score 0. Cleaned Number = +86-021-5466-2808

+66 (02) 261-3525 = Score 0. Cleaned Number = +66-02-261-3525

+44 (020) 7626-0224 = Score 0. Cleaned Number = +44-020-7626-0224

123456 = Score 3. Cleaned Number = 123456

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324690

If you're only interested in the numbers, you can filter out everything else and check the result:

public function phoneNumber($value) {
    $filtered = preg_replace("/\D/","",$value);
    return strlen($filtered) == 10;
}

Upvotes: 5

Related Questions