(1)$str = "Hello world!";
$str_str = str_replace('world','Shanghai',$str);//替换简单的字符串或数组,替换一个字符串,(区分大小写)
print_r($str_str);
//输出:
Hello Shanghai!
(2)$str = "linux is very much php";
$str_str = preg_replace('/linux|php/','java',$str);
print_r($str_str);
//输出:
java is very much java
(3)//把字符串 "Hello world" 替换成 "Hi earth":
$str = array("Hello" => "Hi", "world" => "earth");
$str_str = strtr("Hello world",$str);
print_r($str_str);
//输出:
Hi earth
注:php中在字符串的替换模块有3个函数,str_replace(),preg_replace(),以及strtr()。在编程过程中,这三个函数的执行效率有所不同,str_replace()函数比preg_replace()函数执行效率快,而strtr()函数的执行效率又高于str_replace(),所以在变成中建议使用strtr()函数。
本文介绍了PHP中三种字符串替换函数:str_replace(), preg_replace()及strtr()的使用方法与效率对比。通过具体示例,展示了如何用这些函数进行字符串替换,并强调了strtr()函数在执行效率上的优势。
443

被折叠的 条评论
为什么被折叠?



