Exact Answer Exact Answer - 2 years ago 102
PHP Question

Regular expression works improperly

Here iam trying to write a regular expression to validate phone no in my own sense.
Code is like as follows

$hai = "+458745555---55";
if (!preg_match("/^[\+]{0,1}[0-9\s(\-){0,2}]{6,15}$/", $hai)) {
$valPhone = "Invalid phone number";
} else {
$valPhone = "Valid phone number";

echo $valPhone;


1.possible to come '+' sign in front of the string

2.only digits,-,space are possible in remaining and - should come in between 0-2

3.maximum length of string excluding '+' would be 6-15

4.We couldn't add space start and end of remaining string excluding '+' sign if it found

but the case of '-' is not working fine for me.Any help would be much appreciated..

Answer Source

This regex does the work:

(?=^\+?[^+]{6,15}$)(?!(?:.*-.*){3,})^\+?\d[\d -]+\d$


  • (?=^\+?[^+]{6,15}$) the whole string is 6 to 15 char long and the + is optional;
  • (?!(?:.*-.*){3,}) there can't be more than 2 -;
  • ^\+?\d[\d -]+\d$ the string will contains only digit, spaces and -

See demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download