strtr() - 转换指定字符 - php 字符串函数
strtr()
(PHP 4, PHP 5, PHP 7)
转换指定字符
说明
strtr (string $str , string $from , string $to ) : stringstrtr (string $str , array $replace_pairs ) : string该函数返回 $str 的一个副本,并将在 $from 中指定的字符转换为 $to 中相应的字符。 比如, $from[$n]中每次的出现都会被替换为 $to[$n],其中 $n 是两个参数都有效的位移(offset)。
如果 $from 与 $to 长度不相等,那么多余的字符部分将被忽略。 $str 的长度将会和返回的值一样。
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.
参数
待转换的字符串。
$from字符串中与将要被转换的目的字符 $to 相对应的源字符。
$to字符串中与将要被转换的字符 $from 相对应的目的字符。
$replace_pairs参数 $replace_pairs 可以用来取代 $to 和 $from 参数,因为它是以 array('from' => 'to', ...) 格式出现的数组。
返回值
返回转换后的字符串。
如果 $replace_pairs 中包含一个空字符串("")键,那么将返回 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.
范例
strtr() 范例
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.
使用两个参数的 strtr() 范例
以上例程会输出:
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.
strtr() behavior comparison
以上例程会输出:
1001 ba01
参见
str_replace()
子字符串替换preg_replace()
执行一个正则表达式的搜索和替换
Here's an important real-world example use-case for strtr where str_replace will not work or will introduce obscure bugs:
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!