Re: PHP script for detecting pattern sequences?
| From: | Andrew Ballard | Date: | Fri, 10 Jul 2009 15:19:04 +0000 |
| Subject: | Re: PHP script for detecting pattern sequences? | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-295143@lists.php.net to get a copy of this message | ||
On Fri, Jul 10, 2009 at 10:30 AM, Isaac Dover<isaacdover@gmail.com> wrote:
>> On Wed, Jul 8, 2009 at 11:32 PM, WenDong Zhang <zwd2005@gmail.com> wrote:
>> On Thu, Jul 9, 2009 at 6:00 AM, Per Jessen <per@computer.org> wrote:
>> > A suitable regex might look something like this:
>> >
>> > /([0-9]+)\1+/
>> >
>> > Not tested, probably won't work on the first try. You may need
>> > greediness adjustments.
>> >
>> >
>> > /Per
>>
>> yes
>> (\d+?)\1+ works fine
>>
>>
>>
>> --
>> Best Regards!
>> Wen Dong
> those regex patterns wouldn't solve his problem. he wants to pull
> repetitions from the string _before_ knowing a pattern. those patterns will
> match the entire source string
>
> - isaac
Those patterns look like a pretty good starting point to me. True, the
first captured result of preg_match would be the entire string, but
the submatches array would contain the actual sequence that is
repeated:
<?php
$pattern = '/(\d+?)\1+/';
$subject = '032258064516129032258064516129032258064516129032258064516129';
if (preg_match($pattern, $subject, $matches)) {
var_dump($matches);
}
/*
array(2) {
[0]=>
string(60) "032258064516129032258064516129032258064516129032258064516129"
[1]=>
string(15) "032258064516129"
}
*/
$subject = '037037037037037037037037037037037037037037037037037037037037';
if (preg_match($pattern, $subject, $matches)) {
var_dump($matches);
}
/*
array(2) {
[0]=>
string(60) "037037037037037037037037037037037037037037037037037037037037"
[1]=>
string(3) "037"
}
*/
$subject = '333333333333333333333333333333333333333333333333333333333333';
if (preg_match($pattern, $subject, $matches)) {
var_dump($matches);
}
/*
array(2) {
[0]=>
string(60) "333333333333333333333333333333333333333333333333333333333333"
[1]=>
string(1) "3"
}
*/
?>
Some slight adjustments to the pattern could also be useful.
// This would catch a pattern of any repeating characters, not just
numeric digits
$pattern = '/(.+?)\1+/';
// This would only match if the entire string was a repeated sequence
$pattern = '/^(\d+?)\1+$/';
// This would match the repeated sequence only if the string began
with a repeated sequence.
$pattern = '/^(\d+?)\1+/';
// This would match the repeated sequence only if the string ended
with a repeated sequence.
$pattern = '/(\d+?)\1+$/';
If a string had multiple sequences, you could also use preg_match_all
to find each sequence, but that looks a bit more involved than the OP.
None of these require knowing the sequence in advance. How do they not
satisfy the OP?
Andrew