php中替換字串的實作方法:先建立一個PHP範例檔案;然後透過「str_replace("red","black","red green yellow pink purple");」方法取代字串;最後透過echo輸出替換結果即可。
本教學操作環境:Windows7系統、PHP5.6版,此方法適用於所有品牌電腦。
推薦:《PHP影片教學》
PHP字串取代str_replace()函數四種用法
參數$search,要替換的字串,或陣列
參數$replace,被用來替換的字串或陣列
參數$subject,被查詢的字串或陣列
參數$count,可選,如果被指定,將為設定為替換的次數
傳回值:該函數傳回替換後的陣列或字串(新產生的)
#實例一:字串替換字串
$str1 = str_replace("red","black","red green yellow pink purple"); echo $str1.""; //输出结果为black green yellow pink purple
實例二:字串替換數組鍵值
$arr = array("blue","red","green","yellow"); $str1 = str_replace("red","pink",$arr,$i); print_r($str1);
實例三:數組替換數組,映射替換
$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);
實例四:如$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);
更多程式相關知識,請造訪:程式設計學習課程! !
以上是php中替換字串的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!