I've seen quite a few question on SO about identifying repeating patterns for crazy looking strings and stuff but nothing that will capture a repeating number or a repeating number pattern.
I'm trying to figure out a way to write a function that can identify both of these cases. For example I have a number pattern similar to 14285714285714 with the pattern being 142857-142857-14. In some cases the pattern could be say, 7575757 : 75-75-75-7. I also have a reoccurring number like 55555555 or 55555556.
How could I go about creating a function that determines if a number is either repeating or has a pattern? I guess the repeating number could be seen as a pattern in that sense. I'm kind of at a loss on this and any help on this would be greatly appreciated.
Thank you in advance.
EDIT i also only need to throw true if the pattern or re occurrence is longer than 3 digits.
UPDATE So I tried @stribizhev recommendation with preg_match and was indeed able to detect a pattern. I still need my pattern to be much more precise though. If my number is 4444 preg_match shows my pattern as 44-44. I need to be able to know the difference in 4-4-4-4 and 75-75-75. Can some one help me clarify how I would get a more precise result from the preg_match?
Here's what I have so far.
$num = 4444;
if (count($num) >= 3) {
$result = preg_match('/(\d+)\1/', $num, $matches);
if ($result) {
$repeat = "true";
echo "match: ".$matches[0].", ".$matches[1];
}
}
output: match: 4444, 44
Although this output isn't inaccurate, It's just not as specific as I need it to be. 44 is the pattern, but even more so 4 is the pattern. Just like in 7575, 75 is the pattern.
This pattern does the job:
$pattern = '~
\A # start of the string
# find the largest pattern first in a lookahead
# (the idea is to compare the size of trailing digits with the smallest pattern)
(?= (\d+) \1+ (\d*) \z )
# find the smallest pattern
(?<pattern> \d+? ) \3+
# that has the same or less trailing digits
(?! .+ \2 \z)
# capture the eventual trailing digits
(?= (?<trailing> \d* ) )
~x';
if (preg_match($pattern, $num, $m))
echo 'repeated part: ' . $m[0] . PHP_EOL
. 'pattern: ' . $m['pattern'] . PHP_EOL
. 'trailing digits: ' . $m['trailing'] . PHP_EOL;
demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With