strtr — 转换指定字符(PHP 4, PHP 5, PHP 7)
说明:
string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )
该函数返回 str 的一个副本,并将在 from 中指定的字符转换为 to 中相应的字符。 比如, $from[$n]中每次的出现都会被替换为 $to[$n],其中 $n 是两个参数都有效的位移(offset)。
如果 from 与 to 长度不相等,那么多余的字符部分将被忽略。 str 的长度将会和返回的值一样。
参数:
str
待转换的字符串。
from
字符串中与将要被转换的目的字符 to 相对应的源字符。
to
字符串中与将要被转换的字符 from 相对应的目的字符。
replace_pairs
参数 replace_pairs 可以用来取代 to 和 from 参数,因为它是以 array('from' => 'to', ...) 格式出现的数组。
返回值:
返回转换后的字符串。
如果 replace_pairs 中包含一个空字符串("")键,那么将返回 FALSE。
举例:
Example #1 strtr() 范例
<?php
$addr = strtr($addr, "hadsky", "abcdef");
?>
Example #2 使用两个参数的 strtr() 范例
<?php
$trans = array("hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
以上例程会输出:
hello all, I said hi
Example #3 strtr() 作用比较
<?php
echo strtr("baab", "ab", "01"),"\n";
$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>
以上例程会输出:
1001
ba01
站长解析:
strtr使用string strtr ( string $str , string $from , string $to )格式时from和to参数长度应尽量保证一样;
string strtr ( string $str , array $replace_pairs )格式类似str_replace函数。