更新时间:2023-02-05 21:06:04
第一个区别:
PHP手册的注释部分提供了一个有趣的例子,说明strtr
和str_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);
?>
要执行此操作,请改用"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);
?>
这意味着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:
str_replace :按定义键的顺序工作,因此:
str_replace: it works in the order the keys are defined, so:
"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.