本篇文章給大家帶來的內容是關於php字串替換str_replace()函數的方法有哪些?(四種),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
下面通過本文給大家分享PHP字串替換str_replace()函數4種用法,具體內容如下所示:
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
該函數返回一個字串或者數組。該字串或數組是將subject中全部的search都被replace替換之後的結果。
1、$search,要替換的字串,或數組
2、$replace,被用來替換的字串或數組
3、$subject,被查詢的字串或數組
4、$count,可選,如果被指定,將為設定為替換的次數
5、傳回值:該函數返回替換後的數組或者字串(新產生的)
<?php //執行個體一:字串替換字串 $str1 = str_replace("red","black","red green yellow pink purple"); echo $str1.""; //輸出結果為black green yellow pink purple?><?php //執行個體二:字串替換數組索引值 $arr = array("blue","red","green","yellow"); $str1 = str_replace("red","pink",$arr,$i); print_r($str1);?><?php //執行個體三:數組替換數組,映射替換 $arr1 = array("banana","orange"); $arr2 = array("pitaya","tomato"); $con_arr = array("apple","orange","banana","grape"); $con_rep = str_replace($arr1,$arr2,$con_arr,$count); print_r($con_rep);?><?php //執行個體四:如$search為數組,$replace為字串時 $search = array("banana","grape"); $replace = "tomato"; $arr = array("banana","apple","orange","grape"); $new_arr = str_replace($search,$replace,$arr,$count); print_r($new_arr);?>