Replacement With Callback Using Regular Expressions in PHP
Suppose we have the following string:
<?php
$str = '2+3= 3+5= 7+8=';
?>
Suppose we need to find all constructs of the form number+number= and make it so that the result of the addition appears after the equals sign.
To solve such a problem, it is convenient to use
the function preg_replace_callback, which
works similarly to the function preg_replace
- finds and replaces using a regular expression,
but allows performing additional manipulations
with the found pieces.
The first parameter of the function is the regex, the second - what to replace with, the third - the string in which the replacement is carried out.
In this case, a callback function should be passed to the second parameter, which will be called for each found match.
The first parameter of the callback should specify a variable into which the found match will be placed. This variable will be an array of the captured groups of the found match.
Let's try it in practice. Let's write code that will catch our substrings, while placing the first number in the first group, and the second - in the second:
<?php
$str = '2+3= 3+5= 7+8=';
preg_replace_callback('#(\d+)\+(\d+)=#', function($match) {
var_dump($match);
}, $str);
?>
As a result, our var_dump will work
three times, sequentially outputting the following:
['2+3=', '2', '3']
['3+5=', '3', '5']
['7+8=', '7', '7']
Let's move on. Each match will be replaced
by what the callback returns via return.
Let's, for example, replace each of the sought
substrings with the character '!':
<?php
$str = '2+3= 3+5= 7+8=';
$res = preg_replace_callback('#(\d+)\+(\d+)=#', function($match) {
return '!';
}, $str);
echo $res; // will output '! ! !'
?>
And now let's replace each substring with the sum of the pair of numbers in it:
<?php
$str = '2+3= 3+5= 7+8=';
$res = preg_replace_callback('#(\d+)\+(\d+)=#', function($match) {
return $match[1] + $match[2];
}, $str);
echo $res; // will output '5 8 13'
?>
It turns out that our task is almost solved. It remains to make sure that the sought substring stays in front of the sum of numbers. To do this, we will insert the contents of the zeroth group before the sum:
<?php
$str = '2+3= 3+5= 7+8=';
$res = preg_replace_callback('#(\d+)\+(\d+)=#', function($match) {
return $match[0] . ($match[1] + $match[2]);
}, $str);
echo $res; // will output '2+3=5 3+5=8 7+8=13'
?>
Given a string:
<?php
$str = 'The numbers are 3, 7 and 12';
?>
Replace all numbers in the string with their squares.
Expected result:
'The numbers are 9, 49 and 144'
Given a string:
<?php
$str = '2023-01-15 2022-12-31 2024-05-20';
?>
Convert all dates to the format day.month.year.
Given a string:
<?php
$str = 'Costs: $15, $20, $100';
?>
Increase all prices by 10%.