When to use strtr vs str replace?

Sometimes 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 any 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 syntax, is there any benefit to using one or the other? Are there cases where one would not be enough to get the desired result?

question original: When to use strtr vs str_replace?

 11
Author: Comunidad, 2015-12-01

2 answers

Translation Note: the original question was posed by @andrewtweber and answered by myself on the StackOverflow site in English.

First difference:

An interesting example of a differentiated behavior between strtr and str_replace can be found in the comments section of the PHP manual:

<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>
  • the expected result is: "ZDDB"
  • however, what you get is: "ZDDD" (Because a b le corresponds D according to our arrangement)

To make this work as would be expected, it is best to use strtr:

<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>
  • What returns: "ZDDB"

This means that str_replace takes a more global approach to replacements, while strtr simply translates characters one by one.


Another difference:

Given the following code: (taken from PHP String replacement Speed Comparison):

<?php
$text = "PHP: Hypertext Preprocessor";

$text_strtr = strtr($text
    , array("PHP" => "PHP: Hypertext Preprocessor"
        , "PHP: Hypertext Preprocessor" => "PHP"));
$text_str_replace = str_replace(array("PHP", "PHP: Hypertext Preprocessor")
    , array("PHP: Hypertext Preprocessor", "PHP")
    , $text);
var_dump($text_strtr);
var_dump($text_str_replace);
?>

The resulting lines of text will be:

String (3) " PHP "
string (27) "PHP: Hypertext Preprocessor"


The main explanation:

The reasons for this behavior are:

  • Strtr : sorts its parameters by length, in descending order, so:

    1. will give" more importance " to the longer one, and then it will be translated since the text main IS in itself the longest key of the replacement arrangement.
    2. since all the characters in the main text have already been replaced, then that's where the process ends.
  • Str_replace : works in the order in which the keys were defined, therefore:

    1. finds the key "PHP" in the main text and replaces it with: "PHP: Hypertext Preprocessor", resulting in:

      " PHP: Hypertext Preprocessor: Hypertext Preprocessor".

    2. then find the following key: "PHP: Hypertext Preprocessor" in the resulting text from the previous step, so it is replaced by "PHP", resulting in:

      "PHP: Hypertext Preprocessor".

    3. since there are no more keys to review, the replacement process ends there.
 9
Author: Nicolás, 2017-05-23 12:39:20

Complementing Nicholas ' explanation, the result varies by the behavior of the functions.

  • strtr is made to replace characters, regardless of the shape you use, and it loops through the main string character by character, when it finds a match with the search characters, it replaces it and passes to the next character.
  • str_replace is made to replace substrings, regardless of the source length and target, unlike the previous one they must be individual characters. Then for each element to be searched, the entire main string is traversed, all matches are replaced, and then passed to the next substring... if you go to the example of nicolas, "2 "is replaced everywhere by" B", and in another subsequent search" B "is changed to" D", and because they are separate paths we get" ZDDD "instead of"ZDDB".

In addition to this, response times, no it will be very noticeable with small strings, but the longer the length the longer it will take str_replace .

Suppose we have a main string of 100 characters, and let's go for 10 characters:

  • with str_replace, each character will be searched in the top 100, which will give a total of one thousand searches.
  • with strtr , there being a match ignores the rest of the search in that character, ending in less than 10 searches, and each match will make the searches smaller.

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 there are matches or not.

 5
Author: Willem Franco, 2015-12-17 01:21:45