Reputation: 5407
I have regex to match the US numbers:
\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}
Though I check first three digits as us numbers, I have few area code and want to filter numbrs with this area code only.
$area_code = array(201,202,203,2,04);
Number having first three digits among this array value should only allowed. what modification regex required?
Upvotes: 0
Views: 459
Reputation: 76656
Use implode()
to join the numbers together with the delimiter |
and use it in your regex pattern:
$area_code = array(201,202,203,204);
$p = implode('|', $area_code);
$pattern = '/\(?(?:'.$p.')\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/';
The resulting regex would look like:
\(?(?:201|202|203|2|4)\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}
Which would match the number if they begin with one of the values in the in the $area_code
array. The advantage of this approach over the other one is that this'd let you add custom numbers that doesn't follow any specific pattern. The downside is that it can get slow if there lots of numbers in your array.
Upvotes: 1
Reputation: 4021
The following regular expression should serve your purpose:
\(?20[1-4]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}
Upvotes: 1