php中str_replace和str_ireplace的用法和區別

來源:互聯網
上載者:User

標籤: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的用法和區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.