$str='xyzab abab xhababab';
I want to check whether the string contains ab 3 times continuously. Means ababab
It does not work :
$subject = "xyzab abab xhababab";
$pattern = '/ab{3}/';
preg_match_all($pattern, $subject, $matches2,PREG_OFFSET_CAPTURE);
var_dump($matches2);
You need to wrap the ab
into a grouping construct:
(?:ab){3}
^^^ ^
See the regex demo
The quantifier is applied to the subpattern that stands to the left of it. So, in ab{3}
the {3}
quantifies the b
symbol and it matches abbb
. When you group the subpattern sequence and then set a quantifier to the group , all the subpattern sequence is quantified then.
Note that (?:...)
is a non-capturing group that is used only for grouping, not capturing (ie no separate memory buffer is provided for the substrings matched with this group).
If you do not need the group to capture its match, you can optimize this regular expression into
Set(?:Value)?
. The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. The question mark after the opening bracket is unrelated to the question mark at the end of the regex.
See the IDEONE demo :
$subject = "xyzab abab xhababab";
$pattern = '/(?:ab){3}/';
preg_match_all($pattern, $subject, $matches2,PREG_OFFSET_CAPTURE);
var_dump($matches2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.