tags:

views:

63

answers:

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]$
A: 

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

Deepali
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)
David Dorward
+4  A: 

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+$
Asaph
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
@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?
Asaph
@Asaph: Indeed, that seems to do the trick. ;)
Alix Axel