PHP 使用函數explode()、implode()和join()分割和連接字串,explodeimplode

來源:互聯網
上載者:User

PHP 使用函數explode()、implode()和join()分割和連接字串,explodeimplode
PHP 使用函數explode()、implode()和join()分割和連接字串

通常,我們想查看字串的各個部分。例如,查看句子中的單詞(例如,拼字檢查),或者要將一個網域名稱或電子郵件地址分割成一個個的組件部分。PHP提供了幾個字串函數(和一個Regex函數)來實現此功能。

分割字串:explode()函數,它的函數原型如下所示:

array explode(string separator,string input[,int limit]);

這個函數帶有一個輸入字串作為參數,並根據一個指定的分隔字元字串將字串本身分割為小塊,將分割後的小塊返回到一個數組中。可以通過可選的參數limit來限制分成字串小塊的數量。(此函數區分大小寫)

連接字串:implode()函數,它的函數原型如下所示:

string implode(string separator,array input);

使用implode()或join()函數來實現與函數explode()相反的效果,這兩個函數的效果是一致的。從數組中取出數組元素,然後用第一個傳入的參數字元將它們串連在一起。這個函數的調用同explode()十分相似,但效果卻相反。

例子:

<?php    $str = "He told me:'Hello world! but I don't have any money!'";    echo "原字串:<br>";    var_dump($str);    $ret_arr = explode("e", $str);    echo "用字元‘e’分解字串:<br>";    var_dump($ret_arr);    $ret_arr_3 = explode("e",$str,3);    echo "用字元‘e’分解字串並限制分解為3塊:<br>";    var_dump($ret_arr_3);    $ret_str = implode("i", $ret_arr_3);    echo "用字元‘i’拼接字串數組:<br>";    var_dump($ret_str);

輸出:

原字串:string 'He told me:'Hello world! but I don't have any money!'' (length=53)用字元‘e’分解字串:array  0 => string 'H' (length=1)  1 => string ' told m' (length=7)  2 => string ':'H' (length=3)  3 => string 'llo world! but I don't hav' (length=26)  4 => string ' any mon' (length=8)  5 => string 'y!'' (length=3)用字元‘e’分解字串並限制分解為3塊:array  0 => string 'H' (length=1)  1 => string ' told m' (length=7)  2 => string ':'Hello world! but I don't have any money!'' (length=43)用字元‘i’拼接字串數組:string 'Hi told mi:'Hello world! but I don't have any money!'' (length=53)
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。 http://blog.csdn.net/sinat_36329815/article/details/78335649

相關文章

聯繫我們

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