这篇文章主要讲解了“php函数strtr和str_replace怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“php函数strtr和str_replace怎么使用”吧!
一. str_repalce()用法
str_replace(find,replace,string,count)
find:规定要查找的字符串或数组;
replace:被用来替换的字符串或数组;
string:被查询的字符串或数组;
count:可选,替换的次数
<?php //实例一:字符串替换字符串 $str1 = str_replace("red","black","red green yellow pink purple"); echo $str1; //输出结果为black green yellow pink purple echo "<br>"; //实例二:数组的键值用字符串替换 $arr = array("blue","red","green","yellow"); $str1 = str_replace("red","pink",$arr,$count); print_r($str1); //输出结果 //Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) echo "<br>" . $count; //输出替换次数1 //实例三:数组替换数组,一一映射替换 $arr1 = array("banana","orange"); $arr2 = array("pitaya","tomato"); $con_arr = array("apple","orange","banana","grape"); $con_rep = str_replace($arr1,$arr2,$con_arr,$count1); print_r($con_rep); //输出结果 // Array ( [0] => apple [1] => tomato [2] => pitaya [3] => grape ) echo "<br>" . $count1; //输出替换次数2 //实例四:如$search为数组,$replace为字符串时 $search = array("banana","grape"); $replace = "tomato"; $arr = array("banana","apple","orange","grape"); $new_arr = str_replace($search,$replace,$arr,$count2); print_r($new_arr); //输出结果 //Array ( [0] => tomato [1] => apple [2] => orange [3] => tomato ) echo "<br>" . $count2; //输出替换次数2?>
二. strtr()用法
<?php //用法一:strtr(string,from,to)echo strtr("I Love you","Lo","lO");//用法二:strtr(string,array)$arr = array("Hello" => "Hi", "world" => "earth");echo strtr("Hello world",$arr);?>
三. 效率对比
小编使用apache环境和nginx环境做了测试:5.6版本 str_replace 比 strtr 平均效率高4倍,7.1版本效率基本相同。
感谢各位的阅读,以上就是“php函数strtr和str_replace怎么使用”的内容了,经过本文的学习后,相信大家对php函数strtr和str_replace怎么使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!