When to Use Strtr VS Str_Replace

When to use strtr vs str_replace?

First difference:

An interesting example of a different behaviour between strtr and str_replace is 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);
?>
  • I would expect as result: "ZDDB"
  • However, this return: "ZDDD"
    (Because B = D according to our array)

To make this work, use "strtr" instead:

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

This means that str_replace is a more global approach to replacements, while strtr simply translates the chars 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:

This happens because:

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

    1. it will give "more importance" to the largest one, and then, as the subject text is itself the largest key of the replacement array, it gets translated.
    2. because all the chars of the subject text have been replaced, the process ends there.
  • str_replace: it works in the order the keys are defined, so:

    1. it finds the key “PHP” in the subject text and replaces it with: “PHP: Hypertext Preprocessor”, what gives as result:

      “PHP: Hypertext Preprocessor: Hypertext Preprocessor”.

    2. 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:

      “PHP: Hypertext Preprocessor”.

    3. there are no more keys to look for, so the replacement ends there.

PHP strtr vs str_replace benchmarking

For simple replacements, strtr seems to be faster, but when you have complex replacements with many search strings, it appears that str_replace has the edge.

Understanding how str_replace and strtr works in php

Yes, that is correct. str_replace() does its replacements sequentially, whereas strtr() works through each character in the string and replaces it only once.

strrchr with strtr or str_replace in PHP

Have created custom function. Might be useful:

<?php
$str = 'accélérer';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // accélèrer
echo '<br/><br/>';

$str = 'sécher';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // sècher

function replaceMultiByte($str, $replace, $replaceWith)
{
$exp = explode($replace, $str);

$i = 1;
$cnt = count($exp);
$format_str = '';
foreach($exp as $v)
{
if($i == 1)
{
$format_str = $v;
}
else if($i == $cnt)
{
$format_str .= $replaceWith . $v;
}
else
{
$format_str .= $replace . $v;
}
$i++;
}
return $format_str;
}
?>

Is str_replace faster with array?

From PHP Docs on str_replace :

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;

Looking at those examples, PHP is applying the str_replace for each $search array node so both of your examples are the same in terms of performance however sure using an array for search and replace is more readable and future-prof as you can easily alter the array in future.

PHP replace multiple value using str_replace?

From the manual page for str_replace():

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

For example, "m" is replaced with "Month", then the "h" in "Month" is replaced with "Hours", which comes later in the array of replacements.

strtr() doesn't have this issue because it tries all keys of the same length at the same time:

$date = strtr($key, array(
'y' => 'Year',
'm' => 'Month',
'd' => 'Days',
'h' => 'Hours',
'i' => 'Munites', // [sic]
's' => 'Seconds',
));

how to Str_replace for multiple items

You can use strtr() and an associative array to do this:

<?php
$text = "Text about -- and -+- !";
$replacements = [
"--" => "/",
"-+-" => ":",
];
echo strtr($text, $replacements); // Text about / and : !

To add more replacements, simply keep adding more elements to the $replacements array. Index is the string to look for, value is the replacement.

  • Demo
  • strtr() reference


Related Topics



Leave a reply



Submit