The str_replace Function
The str_replace
function searches for a given
text in a string and replaces it with another. The first
parameter is what we replace, and the second is what
we replace it with. These can be two strings or two arrays.
In the latter case, the corresponding elements of one array
will be replaced with the corresponding elements of the
second array (see examples).
Syntax
str_replace(array|string $search, array|string $replace, string|array $subject, int &$count = null): string|array
Example
Let's replace all letters 'a'
with '!'
:
<?php
echo str_replace('a', '!', 'abcabc');
?>
Code execution result:
'!bc!bc'
Example
Let's replace all letters 'a'
with 1
,
letters 'b'
with 2
, and letters 'c'
with 3
:
<?php
echo str_replace(['a', 'b', 'c'], [1, 2, 3], 'abcabc');
?>
Code execution result:
'123123'
Example
Let's replace the given letters with one common specified character:
<?php
echo str_replace(['a', 'b', 'c'], '!', 'abcabc');
?>
Code execution result:
'!!!!!!'
Example
Let's perform a replacement in each element of the array:
<?php
$arr = ['abc', 'abc', 'abc'];
$res = str_replace('a', '!', $arr);
print_r($res);
?>
Code execution result:
['!bc', '!bc', '!bc']
Example
Case matters:
<?php
echo str_replace('a', '!', 'Abcabc');
?>
Code execution result:
'Abc!bc'
See Also
-
the
str_ireplace
function,
which performs a case-insensitive search and replace -
the
strtr
function,
which also performs search and replace -
the
substr_replace
function,
which cuts out a part of a string and replaces it with another