php 字串替換函數_PHP教程

來源:互聯網
上載者:User
本文章給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()這兩個函數都比較好用,有需要的參考一下。 字元...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.