USA’s phone number validation using Regular expression in PHP
Posted on February 8, 2008
Filed Under php, tips and technique, tutorial
Last day i saw that one of my friend looking for the validation script in PHP which post the phone no (number) of USA from the text box and wanted to validate it from PHP in the following format.
“XXX-XXX-XXXX”
Well, I’ve made a function in PHP for him to validate the north American phone number format.Here is that function which might be useful for you.
function validatePhoneNo($phone)
{
if(ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', $phone))
return true;
else
return false;
}
Now lets look at the explanation of following regular expression I’ve used in ereg() function of PHP.
^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$
The first hat sign (^) represents that it is the beginning of the string. And [2-9]{1} represents that is the first character should be digits ranging from 2 to 9 and the next [0-9]{2} represents that the next two characters should be digits ranging from 0 to 9. And the dash (-) next to it represents that this character must exists. And the next [0-9]{3} means that the next three characters should be digits and the next expression also means that there should be existence of dash (-) and three digits and the last string dollar sign ($) represents that it is the end of the string.
Popularity: 11% [?]
Follow me on twitter at http://twitter.com/roshanbh.
Related Posts
» Php function to validate two decimal places of a number
» Display random number in random way using JavaScript
» Ip address validation in PHP using regular expression
» USA’s Zip Code Validation in PHP
Comments
4 Responses to “USA’s phone number validation using Regular expression in PHP”
Leave a Reply






[...] North American phone number format validation using Regular … By Roshan Last day i saw that one of my friend looking for the validation script in PHP which post the phone no (number) of USA from the text box and wanted to validate it from PHP in the following format. Roshan Bhattarai’s Blog - PHP… - http://roshanbh.com.np [...]
Actually, I don’t think the exchange (middle 3) can start with a 1 or 0 either
thank uuuuuuuuuuuuuuuuuuuuuuuu!
I tried this code in my order form on the site and it works perfectly, just what I needed.
Steve