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% [?]

Enter your email address and get recent tutorials, tips, tricks and scripts of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

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”

  1. PHP Coding School » Blog Archive » php tips [2008-02-08 10:47:10] on February 8th, 2008 10:50 am

    [...] 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 [...]

  2. Kevin on February 9th, 2008 8:18 pm

    Actually, I don’t think the exchange (middle 3) can start with a 1 or 0 either

  3. g.j.srinivas on February 14th, 2008 9:19 am

    thank uuuuuuuuuuuuuuuuuuuuuuuu!

  4. hosting on July 29th, 2008 8:15 pm

    I tried this code in my order form on the site and it works perfectly, just what I needed.

    Steve

Leave a Reply