Is there a difference between strtr and str_replace?


I was looking at how the strtr and str_replace functions behaved and I noticed that, at first glance, the two 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

By taking the way the function parameters are passed, are there any significant differences between them, so that you have to decide which one to use for each specific case?

Or do they both do the same thing?

And if they do, why should the two exist?

asked by anonymous 27.02.2015 / 13:30

2 answers


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

strtr is a bit faster for simple operations, and str_replace does better for more complex operations, based on responses to this question in SO .

In addition, there is a difference in how this comment in the documentation:

$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

See running on ideone .

27.02.2015 / 13:39

From PHP manual :

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

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

27.02.2015 / 13:39