PHP中str_replace函數使用小結

函數原型:mixed str_replace(mixed needle,mixed new_needle,mixed haystack[,int &count]); 
needle:要被替換的字符串,new_needle:替換用的字符串,haystack:操作字符串,count:替換次數【可選參數】 

我們重點試驗前三個在使用數組是的執行方式: 

在都不使用數組時,該函數直接使用new_needle替換所有的needle並返回替換後的字符串。如:str_replace("m","n","my name is jim!")返回ny nane is jin! 

1、只對needle使用數組。 

示例:str_replace(array('m','i'),'n',"my name is jim!");返回:ny nane ns jnn! 
可以看出,函數順序性的對數組中每個字符串進行替換,並返回替換後的字符串。 

2、只對new_needle使用數組。 

示例:str_replace('m',array('n','z'),"my name is jim!\n")返回:Arrayy naArraye is jiArray! 
該替換比較有意思,如果只對第二個參數使用數組則函數將其作爲字符串Array進行使用,將所有的needle替換爲了數組。 

3、只對haystack使用數組。 

示例:str_replace("m","n",array("my name is jim!","the game is over!"))該語句執行結果返回一個數組,即分別爲傳入的兩個字符串替換後的結果。 
如果輸出數組內容會看到:ny nane is jin! the gane is over! 

4、對needle和new_needle都使用數組。 

示例:str_replace(array("m","i"),array("n","z"),"my name is jim!")返回:ny nane zs jzn! 
查看執行結果可以發現,如果前兩個參數都使用數組則函數把數組各個對象項字符串進行了替換,及needle的第一項替換爲new_needle的第一項。以此類推。 

如果needle數組比new_deedle長,例如:str_replace(array("m","i","s"),array("n","z"),"my name is jim!");返回:ny nane z jzn!可見,對於needle數組多出來的字符串被替換爲了空串。 
如果new_needle數組比needle長,例如:str_replace(array("m","i"),array("n","z","x"),"my name is jim!")返回ny nane zs jzn!可見new_needle多餘的項被忽略。 

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 
這個比較好理解,對兩個字符串分別執行替換。 

簡單總結下,防止自己忘記!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章