Pockets in Replacement via Regular Expressions in PHP
When working with the function preg_replace
,
if we put something into a pocket in the regular expression,
then in the replacement string we can insert the contents
of this pocket by writing the dollar sign $ and the
pocket number. For example, $0
- the zero pocket,
$1
- the first pocket, $2
- the second
pocket, and so on.
Let's look at examples to understand what this is for and how to use it.
Example
Let's find all numbers and replace them with the same numbers but in curly braces. To do this, all found numbers will be replaced by themselves, but in curly braces:
<?php
$str = '1 23 456 xax';
$res = preg_replace('#(\d+)#', '{$1}', $str);
?>
As a result, the following will be written to the variable:
'{1} {23} {456} xax'
Example
Let's find all strings representing
numbers with x's around them and replace these
numbers with themselves, but with '!'
signs around:
<?php
$str = 'x1x x23x x456x xax';
$res = preg_replace('#x(\d+)x#', '!$1!', $str);
?>
As a result, the following will be written to the variable:
'!1! !23! !456! xax'
Example
Let's solve the following problem: given strings
of the form 'aaa@bbb'
- letters, then an at sign,
then letters. We need to swap the letters
before '@'
and after. Let's implement it:
<?php
$str = 'aaa@bbb ccc@ddd';
$res = preg_replace('#([a-z]+)@([a-z]+)#', '$2@$1', $str);
?>
As a result, the following will be written to the variable:
'bbb@aaa ddd@ccc'
Practical Tasks
Given a string:
<?php
$str = '12 34 56 78';
?>
Swap the digits in all two-digit numbers.
Given a string with a date:
<?php
$str = '31.12.2025';
?>
Convert this date to '2025.12.31'
.