The strtr Function
The strtr
function performs search and
replacement of characters in a string. It has two modes
of operation.
In the first mode, the function accepts an array of replacements: the keys are what we are replacing, and the values are what we will replace with:
strtr(where we replace, replacement array);
In the second mode, the function accepts one parameter as a string with characters that will be replaced, and the second parameter - a string with characters that will be used for replacement. The corresponding characters of the first string will be replaced by the corresponding characters of the second string:
strtr(where we replace, what we replace, what we replace with);
Example
In this example, the function will replace characters
1
and 2
with 'a'
and 'b'
respectively:
<?php
echo strtr('111222', ['1'=>'a', '2'=>'b']);
?>
Code execution result:
'aaabbb'
Example
In this example, the function will also replace characters
1
and 2
with 'a'
and 'b'
respectively:
<?php
echo strtr('111222', '12', 'ab');
?>
Code execution result:
'aaabbb'
See Also
-
the
str_replace
function,
which also performs search and replace -
the
substr_replace
function,
which cuts out part of a string and replaces it with another