Is there a difference between strtr and str_replace?

Asked

Viewed 1,824 times

11

I was analyzing the way functions behave strtr and str_replace And I noticed that, at first glance, they both seem to do exactly the same thing. Example:

$translators = [
    'da hora' => 'bacana',
    'ser' => 'é',
];

$str = 'O Stack Overflow ser um site da hora';

echo str_replace(array_keys($translators), $translators, $str);
//  O Stack Overflow é um site bacana

echo strtr($str, $translators);
//O Stack Overflow é um site bacana

Apart from the way the function parameters are passed, there is some considerable difference between them, to the point of having to decide which to use for each specific case?

Or both do the same thing?

And, if they do, why exist the two?

  • see if this helps you: http://stackoverflow.com/questions/8177296/when-to-use-strtr-vs-str-replace if you don’t understand, ask for a reply format

2 answers

10


Essentially they do the same thing, but with different results in certain situations and with different speed commitments.

strtr is a little faster for simple operations and str_replace is better for more complex operations, according to the answers to that question in the OR.

In addition there is difference in the second functioning that comment in the documentation:

<?php 
$arrFrom = array("1","2","3","B"); 
$arrTo = array("A","B","C","D"); 
$word = "ZBB2"; 
echo str_replace($arrFrom, $arrTo, $word) . "\n"; //ZDDD

$arr = array("1" => "A","2" => "B","3" => "C","B" => "D"); 
$word = "ZBB2"; 
echo strtr($word,$arr); //ZDDB
?>

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • 1

    Or $arr = array_combine($arrFrom, $arrTo) :)

  • This probably comes from the fact that, in PHP, there is no "array" like the one we found (as in C for example). The worst example in my opinion is the behavior of "implode". (thank you Wallace)

  • @bigowm, analyzing the two situations, it seems to me that the strtr is "better" in terms of accuracy. From what I understand, the str_replace seems to "scan" everything sequentially, according to the array order, causing the "override of what has been replaced". in the old days, I would use the preg_replace only on account of that!

  • 1

    I don’t like saying it better unless it’s clearly better :) But you could say that. For simple things any attempt to use regular expression fatally will be slower.

6

Of PHP manual:

str_replace checks a string subject by the presence of a string search and replaces this string with replace.

strtr checks in a string str by the presence of a string from and replaces each character of from for the corresponding character of to. If the lengths of from and to are different, the extra characters of the longer are ignored.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.