Jump to content

Archived

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

oracle259

Regex and consecutive numbers

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

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Wildbug your a genius. Its much better to just eliminate the 12 possible combinations from consideration that leaves roughly 114 remaining combinations.

Thanks

Share this post


Link to post
Share on other sites
I don't know if you're already checking for it, but one simple regex you [i]can[/i] use to check for repetition is /(\d)\1\1\1/ -- this will find pins with all the same numbers ('1111', '2222', etc).

Share this post


Link to post
Share on other sites

×

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.