The preg_replace Function
The preg_replace
function searches a string for matches with a regular expression
and replaces them with the specified string. The first parameter accepts the regular
expression for the search, the second - the replacement string, the third - the source string.
Additionally, you can specify a replacement limit and a variable for counting replacements.
Syntax
preg_replace(pattern, replacement, subject, [limit], [count]);
Example
Let's replace all digits in the string with the character 'X'
:
<?php
$str = 'a1b2c3';
$res = preg_replace('/\d/', 'X', $str);
echo $res;
?>
Code execution result:
'aXbXcX'
Example
Let's replace only the first 2
matches:
<?php
$str = 'a1b2c3';
$res = preg_replace('/\d/', 'X', $str, 2);
echo $res;
?>
Code execution result:
'aXbXc3'
Example
Using backreferences in replacement:
<?php
$str = 'Hello World';
$res = preg_replace('/(\w+)\s(\w+)/', '$2, $1', $str);
echo $res;
?>
Code execution result:
'World, Hello'
Example
Counting the number of replacements performed:
<?php
$str = 'a1b2c3';
$count = 0;
$res = preg_replace('/\d/', 'X', $str, -1, $count);
echo "Result: $res, Replacements: $count";
?>
Code execution result:
'Result: aXbXcX, Replacements: 3'
See Also
-
the
preg_match
function,
which performs a search using a regular expression -
the
preg_split
function,
which splits a string by a regular expression