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+

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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"

Link to comment
Share on other sites

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];

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.