Reputation: 121
I'm trying to run a test to see if a long string with multiple lines has multiple occurrences of the same pattern, or lets say 5 or 10 occurrences.
So a string like:
$string = "this is a test pattern1 more of a test pattern1
and so on and so on pattern1";
So in this case I was trying in PHP:
if (preg_match('/(pattern1)\1{2,}/m',$string)) print "Found 2+ occurrences of pattern1\n";
Of course this does not work.
And I cannot use preg_match_all
.
Can someone correct my regex please?
Upvotes: 7
Views: 13741
Reputation: 513
Check this pattern
/(pattern1)/g
g - modifier finds all matches instead of returning first match.
Upvotes: 1
Reputation: 11126
why dont you simply search for the word/pattern using preg_match_all and count the number of occurences :
<?php
$message="this is a test pattern1 more of a test pattern1 and one more pattern1";
echo preg_match_all('/pattern1/i', $message, $matches);
will return 3
.
or rather in your case:
<?php
$message="this is a test pattern1 more of a test pattern1 and one more pattern1";
if(preg_match_all('/pattern1/i', $message, $matches) >= 2 ) print "Found 2+ occurences of pattern1\n";
Upvotes: 0
Reputation: 70742
You can use the following..
if (preg_match('/(pattern1)(?:((?!\1).)*\1){2,}/s', $string)) {
Upvotes: 1
Reputation: 89629
If I understand well, you was not far from the good pattern (for three occurrences here):
/(pattern1)(?:.*?\1){2,}/s
where the s modifier allows the dot to match newlines.
Upvotes: 3