I'm having a hard time understanding when strtr
would be preferable to str_replace
or vice versa. It seems that it's possible to achieve the exact same results using either function, although the order in which 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');
This outputs
YeXY XYring
YeZ Zring
YeXY XYring
YeZ Zring
Aside from syntax, is there any benefit to using one over the other? Any cases where one would not be sufficient to achieve a desired result?
First difference:
An interesting example of a different behaviour between
strtr
andstr_replace
is in the comments section of the PHP Manual:To make this work, use "strtr" instead:
This means that
str_replace
is a more global approach to replacements, whilestrtr
simply translates the chars one by one.Another difference:
Given the following code (taken from PHP String Replacement Speed Comparison):
The resulting lines of text will be:
The main explanation:
This happens because:
strtr: it sorts its parameters by length, in descending order, so:
str_replace: it works in the order the keys are defined, so:
then it finds the next key: “PHP: Hypertext Preprocessor” in the resulting text of the former step, so it gets replaced by "PHP", which gives as result:
there are no more keys to look for, so the replacement ends there.