strtr

(PHP 4, PHP 5, PHP 7, PHP 8)

strtr轉(zhuǎn)換指定字符

說明

strtr(string $str, string $from, string $to): string
strtr(string $str, array $replace_pairs): string

該函數(shù)返回 str 的一個(gè)副本,并將在 from 中指定的字符轉(zhuǎn)換為 to 中相應(yīng)的字符。 比如, $from[$n]中每次的出現(xiàn)都會(huì)被替換為 $to[$n],其中 $n 是兩個(gè)參數(shù)都有效的位移(offset)。

如果 fromto 長度不相等,那么多余的字符部分將被忽略。 str 的長度將會(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.

參數(shù)

str

待轉(zhuǎn)換的字符串。

from

字符串中與將要被轉(zhuǎn)換的目的字符 to 相對(duì)應(yīng)的源字符。

to

字符串中與將要被轉(zhuǎn)換的字符 from 相對(duì)應(yīng)的目的字符。

replace_pairs

參數(shù) replace_pairs 可以用來取代 tofrom 參數(shù),因?yàn)樗且? array('from' => 'to', ...) 格式出現(xiàn)的數(shù)組。

返回值

返回轉(zhuǎn)換后的字符串。

如果 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è)參數(shù)的 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

參見