標籤:php
str_replace() 函數定義:使用一個字串替換字串中的另一些字元,對大小寫敏感的搜尋文法:str_replace(find,replace,string,count)str_ireplace() 函數定義:使用一個字串替換字串中的另一些字元,對大小寫不敏感的搜尋文法:str_ireplace(find,replace,string,count)
str_replace詳解
在都不使用數組時,該函數直接使用replace替換所有的search並返回替換後的字串。如:str_replace("m","n","my name is jim!")返回ny nane is jin!
1、只對search使用數組。
樣本:str_replace(array(‘m‘,‘i‘),‘n‘,"my name is jim!");返回:ny nane ns jnn!
可以看出,函數順序性的對數組中每個字串進行替換,並返回替換後的字串。
2、只對replace使用數組。
樣本:str_replace(‘m‘,array(‘n‘,‘z‘),"my name is jim!n")返回:Arrayy naArraye is jiArray!
該替換比較有意思,如果只對第二個參數使用數組則函數將其作為字串Array進行使用,將所有的search替換為了數組。
3、只對subject使用數組。
樣本:str_replace("m","n",array("my name is jim!","the game is over!"))該語句執行結果返回一個數組,即分別為傳入的兩個字串替換後的結果。
如果輸出數組內容會看到:ny nane is jin! the gane is over!
4、對search和replace都使用數組。
樣本:str_replace(array("m","i"),array("n","z"),"my name is jim!")返回:ny nane zs jzn!
查看執行結果可以發現,如果前兩個參數都使用數組則函數把數組各個對象項字串進行了替換,及search的第一項替換為replace的第一項。以此類推。
如果search數組比new_deedle長,例如:str_replace(array("m","i","s"),array("n","z"), "my name is jim!");返回:ny nane z jzn!可見,對於search數組多出來的字串被替換為了空串。
如果replace數組比search長,例如:str_replace(array("m","i"),array("n","z","x"), "my name is jim!")返回ny nane zs jzn!可見replace多餘的項被忽略。
5、三個參數都使用數組。
例如:str_replace(array("m","i"),array("n","z"),array("my name is jim!","the game is over"))返回的數組內容:ny nane zs jzn!the gane zs over
這個比較好理解,對兩個字串分別執行替換。
例子
<?php$find = array("Hello","world");$replace = array("B");$arr = array("Hello","world","!");print_r(str_ireplace($find,$replace,$arr));?>
輸出:
Array([0] => B[1] =>[2] => !)
php中str_replace和str_ireplace的用法和區別