0

I have a variable which has to allow only numbers , dashes and parenthesis, there is no particular length for phone number , And the validation must be done in php , no javascript allowed,

EDIT Just wanted to allow spaces too to the regular expressions....

Thanks

3
  • No particular length? so it isn't going to be a strictly US format? Commented Jun 23, 2012 at 8:02
  • @BenRoux and if not, which countries' formats are allowed? Samantha, your regex will probably have to try and match each country separately. Commented Jun 23, 2012 at 8:06
  • actually i want a variable which just needs to be validated, and the variable shouldnt contain anything other than dashes, paranthesis and numbers Commented Jun 23, 2012 at 8:13

1 Answer 1

2

So, I am a bit confused about the question here, but I'll give it a shot and hopefully it gets you to where you need to be.

This will allow anything containing the specified characters. (303)123-4567 will be allowed. As will 32084248())(21324234--234242-23- (clearly not a phone number)

if( preg_match("/^[0-9() -]+$/", $number) {
    // Only numbers, parens and hypens allowed
}

If you want to make the regex a bit more strict, we can limit to US-style numbers:

if( preg_match("/^\d{0,3}-?(?:\(\d{3}\)|\d{3})-?\d{3}-?\d{4}$/", $number) {
    // US Phone number
}

This will only allow US style numbers with an optional country code.

Sign up to request clarification or add additional context in comments.

4 Comments

hey ben can u tell how to allow spaces too in this
Sure thing. Which should I add it to? the first or second?
can u do it for both ? but now priority is first one :)
THe first one is fixed. The regex there may look confusing, but all it is saying is only allow characters inside the brackets. Simply putting a space inside of them adds your solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.