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<?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:

php'xx ! ! xaaax'

Example

In this example, the search pattern looks like this: letter 'x', letter 'a' two times or more, letter 'x':

php<?php
  $str = 'xx xax xaax xaaax';
  $res = preg_replace('#xa{2,}x#', '!', $str);
?>

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

php'xx xax ! !'

Example

In this example, the search pattern looks like this: letter 'x', letter 'a' three times, letter 'x':

php<?php
  $str = 'xx xax xaax xaaax';
  $res = preg_replace('#xa{3}x#', '!', $str);
?>

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

php'xx xax xaax !'

Example

In this example, the search pattern looks like this: letter 'a' ten times:

php<?php
  $str = 'aaa aaaaaaaaaa aaa';
  $res = preg_replace('#a{10}#', '!', $str);
?>

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

php'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<?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:

php'xx ! ! !'

Example

Zero is also allowed:

php<?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:

php'! ! ! !'

Practice Tasks

Задание 1

Given a string:

php<?php
  $str = 'aa aba abba abbba abbbba abbbbba';
?>

Write a regex that will find the strings 'abba', 'abbba', 'abbbba' and only them.

Задание 2

Given a string:

php<?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).

Задание 3

Given a string:

php<?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).