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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.