-1

A valid phone number is 10 digits, delimited by a dash, and may contain an optional 1-6 digit extension in the format of " x 123456" or " x 123". The following examples would be valid numbers.

123-456-7890 123-456-7890 x 123 123-456-7890 x 1234

The following RegEx works for a 10 digit phone number: /[0-9]{3}-[0-9]{3}-[0-9]{4}/, however when I attempted to add the optional extension like /[0-9]{3}-[0-9]{3}-[0-9]{4}( x [0-9]{1,6})?/ it broke.

Does anyone know what's wrong?

guinness74
  • 35
  • 1
  • 5
  • 2
    Try using shorthand for "whitespace" characters instead of a space, `\s*x\s*`. Also, you will most likely want to anchor your expression to the beginning/end of a string (`^...$`) so that `foo 123-456-7890 bar` is not valid. – Sam Jun 02 '14 at 15:58
  • 1
    Try [googling](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) it. – SaganRitual Jun 02 '14 at 16:02
  • For what it's worth I did Google and search Stack Overflow before asking a new question, and found the question "A comprehensive regex for phone number validation" that was linked to. The answers I saw there were valid RegExs for a multitude of phone number formats, and I wasn't able to figure out where I was going wrong by looking at them. Apologies if I missed the answer in that thread. Ryan Naddy's answer below showed me exactly where I was going wrong specific to my problem. – guinness74 Jun 02 '14 at 16:29

1 Answers1

0

Try using this expression. ( x \d{1,6})? says if 0 or 1 of what is in parentheses.

We are also telling it look at the start and the end of the string as well using ^ and $, and not just look anywhere in the string.

/^\d{3}-\d{3}-\d{4}( x \d{1,6})?$/

Here is an example usage:

<?php

$tests = array(
    "123-456-789",
    "123-456-7890",
    "123-456-7890 x 123",
    "123-456-7890 x 1234",
    "123-456-7890 x 1234654654"
);

foreach($tests as $test){
    if(preg_match("/^\d{3}-\d{3}-\d{4}( x \d{1,6})?$/", $test)){
        echo "<b>$test:</b> valid<br />";
    }else{
        echo "<b>$test:</b> invalid<br />";
    }
}

And here is the output:

123-456-789:               invalid
123-456-7890:              valid
123-456-7890 x 123:        valid
123-456-7890 x 1234:       valid
123-456-7890 x 1234654654: invalid
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338