2

I need to validate phone number in PHP. I have made following regex, but I also need to it to accept numbers starting with plus char, how can I do that?

^[0-9]$
1

3 Answers 3

6

The regex you provided in your question (^[0-9]$) will only match a one digit phone number.

At the very least you probably need to add the + modifier to allow one or more digits:

^[0-9]+$

To add an optional + at the beginning, you'll need to escape it since + is a special character in regular expressions:

^\+?[0-9]+$

And finally, \d is shorthand for [0-9] so you could shorten the expression to

^\+?\d+$
Sign up to request clarification or add additional context in comments.

2 Comments

If there is a + (or a 00) prefixing the number, the ICC has to have at least 1 up to 3 digits, so a more sensible regex would be ^(\+\d{1,3})?\d+$ or ^((\+|00)\d{1,3})?\d+$.
@Alix Axel: I was unaware of that rule. Thank you for pointing it out. Since phone numbers generally need to be more than 3 characters anyway, what do you think about ^\+?\d{4,}$ which is simpler and covers all the bases?
0

Try this:

/^[\+]?([0-9]*)\s*\(?\s*([0-9]{3})?\s*\)?[\s\-\.]*([0-9]{3})[\s\-\.]*([0-9]{4})[a-zA-Z\s\,\.]*[x\#]*[a-zA-Z\.\s]*([\d]*)/

will match:

+1 ( 111)111-1111, #111

111-111-1111

(111)111-1111 x 1

111.111.1111x1

etc.

1 Comment

This unexplained pattern is a messy to be honest. Plusses, dots, commas, and hashes don't need to be escaped inside of a character class. You don't need to use a-zA-Z if you simply add an i pattern modifier. [0-9] and [\d] are simply written as \d. There are questionable usages of quantifiers and needless capture groups in multiple locations. I wouldn't recommend this script to anyone -- even if it did work (well enough) for their application.
0

use this

/^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; 

2 Comments

That doesn't compile (at least in Perl, it might do in PHP), and if it did, then it seems odd to be so specific about the number of digits in a phone number that can start with a + (indicating an international phone number and this a very wide range of lengths and formatting conventions)
{0,1} is simply written as ?. (-{0,1}|\s{0,1}) is more simply written as [-\s]?. Why does this pattern end with a semicolon? Why is the phone number allowed to start with unlimited repetitions of a plus sign followed by a number? Where is the plain English explanation? I wouldn't recommend this answer to anyone -- even if it did work (well enough) for their application.

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.