Jump to content

preg_match for repeating numeric patterms


CorvusPrime

Recommended Posts

I am looking for a preg_match expression that will find recurring numeric patterns in a space delimited list of 1-2 digit numbers.

 

ex: 12 5 6 7 8 7 7 8 7 3 21  and regex should find 787 as the first repeating pattern.

 

New to regex and trying to get my head around this so I can do it lucidly in the future.

 

 

BTW: I have tried the following:

 

/[0-9]{1,2} [0-9]{1,2} [0-9]{1,2}/\1+

 

And what I get is an error about unknown modifier in reference to the final \1+

now wait a minute, that's a different pattern.. "1 2 3" is *a* pattern in that it is sequence of numbers with the same incremented value, but "1 2 3" is not the same pattern definition as "7 8 7" in your example.  In my example, "1 2 3" is not  repeated...

I misread your example. Specifically we are looking for repeating patterns in a string that consists of numbers of up tp two digits and spaces.

 

A second example would be a string such as:

 

1 12 3 4 12 3 4 5 6 2 3 6 2 3 4 1

 

In the above string the number sequence "12 3 4" is repeated once and is the first repeating pattern. That is what I am trying to return with the regex.  The first pattern of three space delimited numbers that are repeated.

hmm...then you must have more to the string than you've mentioned, or else you have some other code not working properly.

 

$string = "2 0 7 1 1 7 1 1 6 8 7";
preg_match('~((\d+\s?){3,}).*\1~',$string,$matches);
$number = $matches[1];

echo $number;

 

that echo's "7 1 1"

oooh actually I found a bug in my pattern...apparently it will match partial numbers.  For example:

 

112 5 6 12 5 7 8 7 5 7 8 7 3 21 12 5 60

 

Pattern will match "12 5 6" that's no bueno...

 

Here is an updated pattern that makes use of lookarounds to make sure it matches whole numbers...

 

$string = "2 0 7 1 1 7 1 1 6 8 7";
preg_match('~(((?<!\d)\d+\s?){3,}).*(?<!\d)\1(?!\d)~',$string,$matches);
$number = $matches[1];

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.