我很难理解什么时候strtr会比str_replace更好,反之亦然。似乎使用这两个函数都可以获得完全相同的结果,尽管子字符串被替换的顺序是相反的。例如:
echo strtr('test string', 'st', 'XY')."\n";
echo strtr('test string', array( 's' => 'X', 't' => 'Y', 'st' => 'Z' ))."\n";
echo str_replace(array('s', 't', 'st'), array('X', 'Y', 'Z'), 'test string')."\n";
echo str_replace(array('st', 't', 's'), array('Z', 'Y', 'X'), 'test string');下面的输出
YeXY XYring
YeZ Zring
YeXY XYring
YeZ Zring除了语法之外,使用一种比另一种更有好处吗?在任何情况下,一个人不足以达到预期的结果?
发布于 2011-11-18 11:26:15
第一个区别:
strtr和str_replace之间的不同行为的一个有趣的例子是在PHP手册的注释部分:
<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>要实现此功能,请改用"strtr“:
<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>这意味着str_replace是一种更具全局性的替换方法,而strtr只是一个接一个地翻译字符。
另一个区别:
给定以下代码(摘自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);
?>生成的文本行将为:
字符串(3) "PHP“
string(27) "PHP:超文本预处理器“
主要解释:
发生这种情况是因为:
它按长度降序对参数进行排序,因此:
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.
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:超文本预处理器”。
3. there are no more keys to look for, so the replacement ends there.
发布于 2011-11-18 11:21:56
似乎使用这两个函数都可以获得完全相同的结果
这并不总是正确的,这取决于您提供的搜索和替换数据。有关这两个函数不同的示例,请参见:Does PHP str_replace have a greater than 13 character limit?
strtr不会替换已经被替换的字符串部分- replaces.strtr内部的right.str_replace将替换str_replace将首先从最长的键开始,以防您使用两个参数调用它- str_replace将从左替换到strtr可以返回替换完成的数量-strtr不提供这样的计数值。发布于 2011-11-18 11:48:34
我认为strtr在使用两个参数时提供了更灵活和有条件的替换,例如:如果string是1,则替换为a,但如果string为10,则替换为b。这一技巧只能通过strtr实现。
$string = "1.10.0001";
echo strtr($string, array("1" => "a", "10" => "b"));
// a.b.000a 请参阅:Php Manual Strtr
https://stackoverflow.com/questions/8177296
复制相似问题