USA’s phone number validation using Regular expression in PHP

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 free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

Related Posts

» Php function to validate two decimal places of a number
» Getting random number between range of two numbers in JavaScript
» Characteristics of experienced programmer
» W3c markup validation and Big websites - Is it really needed?

4 Comments on “USA’s phone number validation using Regular expression in PHP”

  • Kevin wrote on 9 February, 2008, 20:18

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

  • g.j.srinivas wrote on 14 February, 2008, 9:19

    thank uuuuuuuuuuuuuuuuuuuuuuuu!

  • hosting wrote on 29 July, 2008, 20:15

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

    Steve

Trackbacks

  1. PHP Coding School » Blog Archive » php tips [2008-02-08 10:47:10]

Write a Comment

 


Copyright © 2009 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.