1

I have been trying to solve a PHP regular expression problem for awhile now but I just can't quite get it done. I need write a regex that will match between 7 and 12 digits (0..9) and there may optionally be either a single hyphen or a single space between adjacent digits. This is what I have so far...

$match1 = preg_match('/^\d[0-9\-\s]{5,10}\d$/', $number);
$match2 = preg_match('/(-\s|\s-|--|\s\s)/', $number);

As you can see I have to use two different checks and it still isn't enough for me as I can input this string: "1-2-3-4-5" and it will still pass because there are a total of 9 characters but it should fail because there are only 5 digits.

Any help on the matter would be great, thanks!

Filburt
  • 17,626
  • 12
  • 64
  • 115
lewisqic
  • 1,943
  • 5
  • 21
  • 19

4 Answers4

3

How about:

/^(\d[-\s]?){6,11}\d$/
slebetman
  • 109,858
  • 19
  • 140
  • 171
2

Try this regular expression:

/^\d(?:[-\s]?\d){6,11}$/

This allows seven to twelve digits that may be separated by a hyphen or a whitespace character.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
1
^(?:\d[-\s]?){6,11}\d$
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

Try this regex:

\d([-\s]?\d){6,11}
Victor Hurdugaci
  • 28,177
  • 5
  • 87
  • 103