Reputation: 5469
Is it normal regex for validating NAPN numbers? And no "optimizations" possible?
^\+1[2-9](0(?!0)|1(?!1)|2(?!2)|3(?!3)|4(?!4)|5(?!5)|6(?!6)|7(?!7)|8(?!8)|9(?!9))[0-9][2-9]((0|[2-9]){2}|1(?!1)[0-9]|(0|[2-9])1)[0-9]{4}$
Upvotes: 2
Views: 4130
Reputation: 7880
Your link contains info for the match:
NPA (Numbering Plan Area Code) - Allowed ranges: [2–9] for the first digit, and [0-9] for the second and third digits. When the second and third digits of an area code are the same, that code is called an easily recognizable code (ERC). ERCs designate special services; e.g., 888 for toll-free service. The NANP is not assigning area codes with 9 as the second digit.
NXX (Central Office) - Allowed ranges: [2–9] for the first digit, and [0–9] for both the second and third digits (however, the third digit cannot be "1" if the second digit is also "1").
xxxx (Subscriber Number) -[0–9] for each of the four digits.
If you want to omit the +1
at the beginning, then you can use the following to match the 10 digit number. The only thing they're preventing is a number containing some of the 3-digit local codes like 911
, 611
, 411
, etc. So to make this work we're making sure that the next 2 digits after the first in the central office portion of the number are not ones (?!11)
with a negative look-ahead.
This pattern should work for most strings.
$pattern = '~^\(?([2-9][0-9]{2})\)?[-. ]?([2-9](?!11)[0-9]{2})[-. ]?([0-9]{4})$~';
$numbers = array(
'(800) 555 1212',
'(800) 911 1212',
'(800) 910 1212',
'(800) 901 1212',
'(100) 455 1212',
'(800) 155 1212',
'555 555 1212',
'813.555.1212',
);
foreach($numbers as $number){
if(preg_match($pattern,$number)){
echo "$number is valid.\n";
} else {
echo "$number is invalid. \n";
}
}
Output
(800) 555 1212 is valid.
(800) 911 1212 is invalid.
(800) 910 1212 is valid.
(800) 901 1212 is valid.
(100) 455 1212 is invalid.
(800) 155 1212 is invalid.
555 555 1212 is valid.
813.555.1212 is valid.
Upvotes: 7