(PHP 4, PHP 5, PHP 7, PHP 8)
strtr — 轉換指定字符
$str
, string $from
, string $to
): string$str
, array $replace_pairs
): string
該函數返回 str
的一個(gè)副本,并將在 from
中指定的字符轉換為 to
中相應的字符。
比如, $from[$n]
中每次的出現都會(huì )被替換為
$to[$n]
,其中 $n
是兩個(gè)參數都有效的位移(offset)。
如果 from
與 to
長(cháng)度不相等,那么多余的字符部分將被忽略。 str
的長(cháng)度將會(huì )和返回的值一樣。
If given two arguments, the second should be an array in the
form array('from' => 'to', ...)
. The return value is
a string where all the occurrences of the array keys have been
replaced by the corresponding values. The longest keys will be tried first.
Once a substring has been replaced, its new value will not be searched
again.
In this case, the keys and the values may have any length, provided that
there is no empty key; additionally, the length of the return value may
differ from that of str
.
However, this function will be the most efficient when all the keys have the
same size.
str
待轉換的字符串。
from
字符串中與將要被轉換的目的字符 to
相對應的源字符。
to
字符串中與將要被轉換的字符 from
相對應的目的字符。
replace_pairs
參數 replace_pairs
可以用來(lái)取代 to
和 from
參數,因為它是以 array('from' => 'to', ...)
格式出現的數組。
返回轉換后的字符串。
如果 replace_pairs
中包含一個(gè)空字符串(""
)鍵,那么將返回 false
。
If the str
is not a scalar
then it is not typecasted into a string, instead a warning is raised and
null
is returned.
示例 #1 strtr() 范例
<?php
$addr = strtr($addr, "???", "aao");
?>
The next example shows the behavior of strtr() when
called with only two arguments. Note the preference of the replacements
("h"
is not picked because there are longer matches)
and how replaced text was not searched again.
示例 #2 使用兩個(gè)參數的 strtr() 范例
<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
以上例程會(huì )輸出:
hello all, I said hi
The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings.
示例 #3 strtr() behavior comparison
<?php
echo strtr("baab", "ab", "01"),"\n";
$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>
以上例程會(huì )輸出:
1001 ba01