⊗ppPmRgGB 225 of 447 menu

Grouping Parentheses in PHP Regex

In previous examples, repetition operators acted only on one character that was before them. What to do if we want to apply them to several characters?

For this, there are grouping parentheses '(' and ')'. They work like this: if something is in grouping parentheses and immediately after ')' there is a repetition operator - it will act on everything inside the parentheses.

In the next example, the search pattern looks like this: letter 'x', then string 'ab' one or more times, then letter 'x':

<?php $str = 'xabx xababx xaabbx'; $res = preg_replace('#x(ab)+x#', '!', $str); ?>

As a result, the following will be written to the variable:

'! ! xaabbx'

Given a string:

<?php $str = 'ab abab abab abababab abea'; ?>

Write a regex that will find strings by the pattern: string 'ab' repeated 1 or more times.

byenru