Curly Braces in PHP Regular Expressions
The operators +, *, ? are good,
however, they cannot specify an exact
number of repetitions. In this case, the operator
{} will come to your aid.
It works as follows: {5}
- five repetitions, {2,5} - repeats
from two to five (both inclusive), {2,}
- repeats two or more times.
Example
In this example, the search pattern looks like this:
letter 'x', letter 'a' one
or two times, letter 'x':
<?php
$str = 'xx xax xaax xaaax';
$res = preg_replace('#xa{1,2}x#', '!', $str);
?>
As a result, the following will be written to the variable:
'xx ! ! xaaax'
Example
In this example, the search pattern looks like this:
letter 'x', letter 'a' two
times or more, letter 'x':
<?php
$str = 'xx xax xaax xaaax';
$res = preg_replace('#xa{2,}x#', '!', $str);
?>
As a result, the following will be written to the variable:
'xx xax ! !'
Example
In this example, the search pattern looks like this:
letter 'x', letter 'a' three
times, letter 'x':
<?php
$str = 'xx xax xaax xaaax';
$res = preg_replace('#xa{3}x#', '!', $str);
?>
As a result, the following will be written to the variable:
'xx xax xaax !'
Example
In this example, the search pattern looks like this:
letter 'a' ten times:
<?php
$str = 'aaa aaaaaaaaaa aaa';
$res = preg_replace('#a{10}#', '!', $str);
?>
As a result, the following will be written to the variable:
'aaa ! aaa'
Example
In this example, the code author wanted this pattern:
letter 'x', letter 'a' three
times or less, letter 'x',
but unfortunately, this - {,3} -
does not work. You need to specify it explicitly:
<?php
$str = 'xx xax xaax xaaax';
$res = preg_replace('#xa{1,3}x#', '!', $str);
?>
As a result, the following will be written to the variable:
'xx ! ! !'
Example
Zero is also allowed:
<?php
$str = 'xx xax xaax xaaax';
$res = preg_replace('#xa{0,3}x#', '!', $str);
?>
As a result, the following will be written to the variable:
'! ! ! !'
Practice Tasks
Given a string:
<?php
$str = 'aa aba abba abbba abbbba abbbbba';
?>
Write a regex that will find the strings
'abba', 'abbba', 'abbbba'
and only them.
Given a string:
<?php
$str = 'aa aba abba abbba abbbba abbbbba';
?>
Write a regex that will find strings
like 'aba', in which 'b' occurs
less than three times (inclusive).
Given a string:
<?php
$str = 'aa aba abba abbba abbbba abbbbba';
?>
Write a regex that will find strings
like 'aba', in which 'b' occurs
more than four times (inclusive).