Description |
This regex matches all landline phone numbers in Italy.
I have assigned a name to each group so that you can extract the groups, concatenate them and check whether or not the string is made of 10 characters.
I have trid to achieve this goal with lookahead and lookbacks but those methods could be deceived by phone numbers with more than 10 characters becuase of the brackets, the blank spaces and the dashes. Then I tought that this was the best solution.
Here's an example php script to validate a phone number:
$phoneNumber = [Your phone number];
$regex = "/^(?<countryCode>((\+)39)[ ]?)?\(?(?<areaCode>0\d{2,3})\)?[ \-]?(?<centralOfficeCode>\d{3})[ \-]?(?<lineNumber>\d{3,4})$/";
//I make sure that the string matches the regex
if(preg_match($regex, $phoneNumber)){
/*The string matches the regex, now i have to make sure the
phone number is made by 10 characters. */
preg_match($regex, $phoneNumber, $matches);
if(strlen($matches["areaCode"].$matches["centralOfficeCode"].$matches["lineNumber"]) == 10){
echo "Valid phone number";
} else {
echo "Invalid phone number";
}
} else {
echo "Invalid phone number";
}
PS: If all the digit are not separated by blank spaces or dashes the areaCode group will be made by 4 digits but the script works the same. |