There are times when it is difficult to understand when it is preferable to use strtr
and when to use str_replace
. It seems that it is possible to get the same result with either of them, although the order in which the substrings are replaced is reversed. For example:
echo strtr('test string', 'st', 'XY')."\n";
echo strtr('test string', array( 's' => 'X', 't' => 'Y', 'st' => 'Z' ))."\n";
echo str_replace(array('s', 't', 'st'), array('X', 'Y', 'Z'), 'test string')."\n";
echo str_replace(array('st', 't', 's'), array('Z', 'Y', 'X'), 'test string');
Delivery as output:
YeXY XYring
YeZ Zring
YeXY XYring
YeZ Zring
Aside from the syntax, is there any benefit to using one or the other? Are there cases where one would not be enough to obtain the desired result?
Original question: When to use strtr vs str_replace?