-1

I would like to detect whether a user-chosen pin contains 4 identical numbers e.g 1111 or 2222. I'm using preg_match in PHP.

How can I adapt this answer to do this?

Community
  • 1
  • 1
codecowboy
  • 9,835
  • 18
  • 79
  • 134
  • Seeing as how the pin would usually not be embedded in any other data, isn't a non-regex approach of seeing if a string consists of the same, repeated value more maintainable for you? – hexparrot Jul 17 '12 at 14:50

3 Answers3

9

You could use this regex:

/(\d)\1{3}/

This matches a single digit (\d), and then matches that same digit 3 times \1{3}.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • 5
    this is called back referencing http://php.net/manual/en/regexp.reference.back-references.php – Waygood Jul 17 '12 at 14:50
2
count(array_unique(str_split($pin))) > 1
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 1
    I like this solution, but you'd have to make sure `$pin` consisted of only numbers beforehand and it's length is 4. Otherwise, things like `aaaa` and even `1` will validate. – nickb Jul 17 '12 at 14:53
  • Nice one, although I find it strange that you would need a regex or 3 string (or more?) functions just to check for 4 repeating numbers. I would have thought it would be simpler... – jeroen Jul 17 '12 at 14:55
  • @nickb a pin typically is just 4 numbers, but I suppose it could be different in this case. – Explosion Pills Jul 17 '12 at 14:58
1

Adapting from the answer you link to:

\b(\d)\1{3}\b

Instead of using \1+ that would match any number of repetitions of the first digit, you substitute it with \1{3} that will only allow three repetitions of the first digit, thus giving you the desired four digits when matched.

Or if you prefer:

\b(\d)\1\1\1\b
Ernesto
  • 3,837
  • 6
  • 35
  • 56