本文章給php初學者講了兩個php中執行個體的字元替換函數,一個是str_ireplace()一個是substr_replace()這兩個函數都比較好用,有需要的參考一下。
字串的替換技術可以通過以下兩個常用函數實現:str_ireplace()函數和substr_replace()函數
str_ireplace()函數
使用新的子字串替換原始字串中被指定要替換的字串,文法:
mixed str_ireplace(mixed search,mixed replace,mixed subject[,int&count])
參數search:必要參數,指定需要尋找的字串。
參數replace:必要參數,指定替換的值。
參數subject:必要參數,指定尋找的範圍。
參數count:選擇性參數,(帶中括弧的為選擇性參數),擷取執行替換的數量。
執行個體:
| 代碼如下 |
複製代碼 |
$str2=”某某”; $str1=”**”; $str=”某某網站的地址是www.hzhuti.com ,某某網站主要記錄一些學習php的筆記和感想以及各種軟體知識”; echo str_ireplace($str2,$str1,$str); //str2尋找的值,str1替換的值,str範圍 ?> |
在本例中,我們將示範帶有數組和 count 變數的 str_ireplace() 函數:
| 代碼如下 |
複製代碼 |
$arr = array("blue","red","green","yellow"); print_r(str_ireplace("red","pink",$arr,$i)); echo "Replacements: $i"; ?> 輸出: Array ( [0] => blue [1] => pink [2] => green [3] => yellow ) |
Replacements: 1例子 3
| 代碼如下 |
複製代碼 |
$find = array("Hello","world"); $replace = array("B"); $arr = array("Hello","world","!"); print_r(str_ireplace($find,$replace,$arr)); ?>輸出: Array ( [0] => B [1] => [2] => ! )
|
substr_replace()函數
對指定字串中的部分字串進行替換,文法:
string substr_replace(string str,string repl,int start,[int length])
參數str:指定要操作的原始字串。
參數repl:必要參數,指定替換後的新字串。
參數start:指定替換字串開始的位置。
參數length:指定返回的字串長度。
執行個體:
| 代碼如下 |
複製代碼 |
substr_replace('eggs','x',-1,-1); //eggxs substr_replace('eggs','x',-1,-2); //eggxs substr_replace('eggs','x',-1,-2); //eggxs ?> Same as: substr_replace('eggs','x',-1,0); //eggxs ?> substr_replace('huevos','x',-2,-2); //huevxos substr_replace('huevos','x',-2,-3); //huevxos substr_replace('huevos','x',-2,-3); //huevxos ?> Same as: substr_replace('huevos','x',-2,0); //huevxos ?> |
更多詳細內容請查看:http://www.bKjia.c0m/phper/21/32954.htm
http://www.bkjia.com/PHPjc/631687.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631687.htmlTechArticle本文章給php初學者講了兩個php中執行個體的字元替換函數,一個是str_ireplace()一個是substr_replace()這兩個函數都比較好用,有需要的參考一下。 字元...