且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

何时使用strtr vs str_replace?

更新时间:2023-02-05 21:06:04

第一个区别:

PHP手册的注释部分提供了一个有趣的例子,说明strtrstr_replace之间的不同行为:

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);
?>

  • 我希望结果是:"ZDDB"
  • 但是,此返回:"ZDDD" (因为根据我们的数组,B = D)
    • I would expect as result: "ZDDB"
    • However, this return: "ZDDD" (Because B = D according to our array)
    • 要执行此操作,请改用"strtr":

      To make this work, use "strtr" instead:

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

  • 这将返回:"ZDDB"
  • 这意味着str_replace是一种更全局的替换方法,而strtr只是简单地逐个转换字符.

    This means that str_replace is a more global approach to replacements, while strtr simply translates the chars one by one.

    另一个区别:

    给出以下代码(摘自 PHP字符串替换速度比较 ):

    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);
?>

结果文本行将是:

string(3)"PHP"
string(27)"PHP:超文本预处理器"

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


主要解释:

发生这种情况是因为:

  • strtr :它按长度降序对参数进行排序,因此:

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

  1. 它将使最大的字符更重要",然后,由于主题文本本身是替换数组的最大键,因此将其翻译.
  2. 因为主题文本的所有字符已被替换,所以该过程到此结束.

  • str_replace :按定义键的顺序工作,因此:

  • str_replace: it works in the order the keys are defined, so:

      它在主题文本中找到键"PHP",并将其替换为:"PHP:超文本预处理器",其结果如下:
    1. it finds the key "PHP" in the subject text and replaces it with: "PHP: Hypertext Preprocessor", what gives as result:

    "PHP:超文本预处理器:超文本预处理器".

    "PHP: Hypertext Preprocessor: Hypertext Preprocessor".

  • 然后在上一步的结果文本中找到下一个键:"PHP:超文本预处理器",因此将其替换为"PHP",其结果为:

  • 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:超文本预处理器".

    "PHP: Hypertext Preprocessor".

  • 没有更多要查找的键,因此替换在此处结束.

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