Jump to content

Regex and consecutive numbers


oracle259

Recommended Posts

The aim of the exercise is to ban users from selecting weak PINs. Each PIN starts with 1 uppercase letter and ends with 4 numbers. eg A2587. However, a PIN such as A1234 could be easily guessed. Therefore, my questions are:

1. How do i go about creating an expression that matches the uppercase letter and 4 consecutive numbers? eg A2345, B2345, C2345, etc

2. How do i make the expression sensitive to ascending or descending order?
eg A2345, A5432 or B2345, B5432.


Thanks in advance
Link to comment
https://forums.phpfreaks.com/topic/13888-regex-and-consecutive-numbers/
Share on other sites

[code]<?php

$tests = array(
### Should Fail.
'A2345',
'B2345',
'C2345',
'A5432',
'B4321',
'C0123',
### Should Pass.
'A1235',
'B2367',
'C5431',
'A1385',
'B9870',
'C1111',
);

foreach ($tests as $test) {
echo "<b>Testing '$test':</b>";
### Match the digits on the ends (the first and fourth).
preg_match('/(\d).+(\d)/', $test, $digits);
### Get rid of the full pattern match.
array_shift($digits);
### There is no consecutive pattern if they are equal.
if ($digits[0] == $digits[1]) {
echo 'Not Consecutive';
continue;
}
### Find the high and low; assign them to variables.
if ($digits[0] < $digits[1]) {
list($low, $high) = $digits;
}
else {
list($high, $low) = $digits;
}
### Create a range.
$range = range($low, $high);
### There are only 4 numbers, so if they are consecutive our
### range should be 4.
echo count($range) == 4 ? 'Consecutive' : 'Not Consecutive' ;
echo '<br />';
}
?>[/code]
Aren't there only twelve possiblities?

1234, 2345, 3456, 4567, 5678, 6789
9876, 8765, 7654, 6543, 5432, 4321

[code]preg_match('/1234|2345|3456|4567|5678|6789|9876|8765|7654|6543|5432|4321/',$pin)[/code]

It's not elegant, but it's easier than trying to make an abstract search pattern, which I don't think can be done in one step with regex.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.