Re: Regex for telephone numbers
| From: | Steve Staples | Date: | Fri, 31 Dec 2010 17:56:51 +0000 |
| Subject: | Re: Regex for telephone numbers | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-310436@lists.php.net to get a copy of this message | ||
On Wed, 2010-12-29 at 19:35 -0500, Daniel P. Brown wrote:
> On Wed, Dec 29, 2010 at 19:12, Ethan Rosenberg <ethros@earthlink.net> wrote:
> > Dear List -
> >
> > Thank you for all your help in the past.
> >
> > Here is another one....
> >
> > I would like to have a regex which would validate that a telephone number
> > is in the format xxx-xxx-xxxx.
>
> Congrats. People in Hell would like ice water. Now we all know
> that everyone wants something. ;-P
>
> Really, this isn't a PHP question, but rather one of regular
> expressions. That said, something like this (untested) should work:
>
> <?php
>
> $numbers = array(
> '123-456-7890',
> '2-654-06547',
> 'sf34-asdf-',
> 'abc-def-ghij',
> '555_555_5555',
> '000-000-0000',
> '8007396325',
> '241-555-2091',
> '800-555-0129',
> '900-976-739',
> '5352-342=452',
> '200-200-2000',
> );
>
> foreach ($numbers as $n) {
> echo $n.(validate_phone($n) ? ' is ' : ' is not ').'a valid
> US/Canadian telephone number.'.PHP_EOL;
> }
>
>
> function validate_phone($number) {
>
> if
> (preg_match('/^[2-9]{1,}[0-9]{2,}\-[2-9]{1,}[0-9]{2,}\-[0-9]{4,}$/',trim($number)))
> {
> return true;
> }
>
> return false;
> }
> ?>
>
^^^^ THIS ^^^^
is the regex you want to use... it is the most complete one that has
been posted here, and it works.