Reputation: 71
Not sure if regular expressions are the right approach for this, but here is what I am looking to achieve... within a string composed of sorted digits such as 23412167894125123 I would like to extract all sequences of at least 3 consecutive digits:
Can this be done with regex? Otherwise what could be a sensible approach?
Upvotes: 1
Views: 875
Reputation: 1517
If the regex looks too complex, this function uses a simple for loop
function findSeq($string) {
$seq_started = false;
$seq = '';
$list = [];
for ($i = 1; $i < strlen($string) + 1; $i++) {
@$curr = $string[$i];
$prev = $string[$i - 1];
@$next = $string[$i + 1];
if ($prev + 1 == $curr) {
if ($seq_started === false) {
$seq .= "$prev$curr";
} else {
$seq .= $curr;
}
$seq_started = true;
continue;
}
if ($seq_started === true) {
if (strlen($seq) > 2) {
$list[] = $seq;
}
$seq = '';
$seq_started = false;
}
}
return $list;
}
print_r(findSeq('2341216789412501231456789'));
Output
Array
(
[0] => 234
[1] => 6789
[2] => 0123
[3] => 456789
)
Upvotes: 1
Reputation: 18671
With RegEx, you can use:
(123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)
Try here: https://regex101.com/r/Ap8C2D/1
If you test also with 012…:
(012(?:3(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?)?|123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)
Test: https://regex101.com/r/zm6I9x/1
Upvotes: 4
Reputation: 6131
You could use RegEx, but to be honest this would be much simpler to implement a loop and check if the numbers are sequential inside of the loop. Take a look at this example:
$literal = '23412167894125123';
for ($c = 0; $c < strlen($literal) - 2; $c++) {
if(intval($literal[$c]) + 1 == intval($literal[$c + 1]) &&
intval($literal[$c]) + 2 == intval($literal[$c + 2])) {
echo $literal[$c], $literal[$c + 1], $literal[$c + 2], '<br />';
}
}
Fiddle: Live Demo
Upvotes: 2