php函数之strtr和str_replace的用法详解以及效率分析 原创

PHP中主要用strtr()和str_repalce()这两个函数替换字符串和数组,但你们都知道他们这两个函数的区别和用法吗?有不少文章在说使用strtr函数比str_replace快4倍,那为什么很多时候都在用str_replace,到底应该使用哪个函数呢

PHP中主要用strtr()和str_repalce()这两个函数替换字符串和数组,但你们都知道他们这两个函数的区别和用法吗?有不少文章在说使用strtr函数比str_replace快4倍,那为什么很多时候都在用str_replace,到底应该使用哪个函数呢?

一. str_repalce()用法

str_replace(find,replace,string,count)
find:规定要查找的字符串或数组;
replace:被用来替换的字符串或数组;
string:被查询的字符串或数组;
count:可选,替换的次数

"; //实例二:数组的键值用字符串替换 $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 "
" . $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 "
" . $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 "
" . $count2; //输出替换次数2 ?>

 

二. strtr()用法

 

 "Hi", "world" => "earth"); echo strtr("Hello world",$arr); /*输出结果: Hi earth*/ ?>

三. 效率对比

笔者使用apache环境和nginx环境做了测试:5.6版本 str_replace 比 strtr 平均效率高4倍,7.1版本效率基本相同。

四. 总结

使用strtr会出现一些不可控的错误,strtr被查询替换的只能是字符串,而且str_replace函数比strtr效率高、速度快,因此推荐使用str_replace函数替换字符串或数组。

到此这篇关于php函数之strtr和str_replace的用法详解以及效率分析的文章就介绍到这了,更多相关php函数strtr和str_replace对比内容请搜索0133技术站以前的文章或继续浏览下面的相关文章。希望大家以后多多支持0133技术站!

以上就是php函数之strtr和str_replace的用法详解以及效率分析 原创的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » PHP编程