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?
Translation Note: The original question was posed by @andrewtweber and answered by myself on the English StackOverflow site.
First difference:
An interesting example of differentiated behavior between
strtr
andstr_replace
is found in the comments section of the PHP manual:To make this work as expected, it's best to use
strtr
:This means that it
str_replace
takes a more global approach to replacements, whilestrtr
simply translating characters one by one.Other difference:
Given the following code: (taken from PHP String Replacement Speed Comparison ):
The resulting lines of text will be:
The main explanation:
The reasons for this behavior are:
strtr : sort its parameters by length, in descending order, so:
str_replace : works in the order the keys were defined, so:
Complementing Nicolás's explanation, the result varies by the behavior of the functions.
In addition to this, response times won't be very noticeable with small strings, but the longer the length, the longer it will take for str_replace .
Suppose we have a main string of 100 characters, and let's go find 10 characters:
So if there are matches with strtr less than a thousand searches will be done, while with str_replace the thousand searches will always be done, regardless of whether or not there are matches.