PHP 字串擷取 substr 與 strstr 函數-來自PHP教程

來源:互聯網
上載者:User

標籤:class   c   tar   http   a   int   

PHP 字串擷取 substr 與 strstr 函數PHP 字串擷取

用於從字串中擷取指定字串。

相關函數如下:

  • substr():從字串中擷取其中的一部分
  • strstr():尋找字串在另一個字串中第一次出現的位置,並返回從該位置到字串結尾的所有字元
  • subchr():同 strstr()
  • strrchr():尋找字串在另一個字串中最後一次出現的位置,並返回從該位置到字串結尾的所有字元
substr()

substr() 函數用於從字串中擷取其中的一部分,返回一個字串。

文法:

string substr ( string string, int start [, int length] )
參數說明如下:
參數 說明
string 要處理的字串
start 字串開始位置,起始位置為 0 ,為負則從字串結尾的指定位置開始
length 可選,字串返回的長度,預設是直到字串的結尾,為負則從字串末端返回

例子:

<?phpecho substr(‘abcdef‘, 1);      //輸出 bcdefecho substr(‘abcdef‘, 1, 2);   //輸出 bcecho substr(‘abcdef‘, -3, 2);  //輸出 deecho substr(‘abcdef‘, 1, -2);  //輸出 bcd?>
提示

如果 start 是負數且 length 小於等於 start ,則 length 為 0。

strstr()

尋找字串在另一個字串中第一次出現的位置,並返回從該位置到字串結尾的所有字元,如果沒找到則返回 FALSE。

文法:

string strstr ( string string, string needle )
參數說明如下:
參數 說明
string 要處理的字串
needle 要尋找的字串,如果是數字,則搜尋匹配數字 ASCII 值的字元

例子:

<?php$email = ‘[email protected]‘;$domain = strstr($email, ‘@‘);echo $domain;// 輸出 @5idev.com?>
提示

該函數對大小寫敏感。如需進行大小寫不敏感的尋找,請使用 stristr() 。

strchr()

同 strstr() 。

strrchr()

尋找字串在另一個字串中最後一次出現的位置,並返回從該位置到字串結尾的所有字元,如果沒找到則返回 FALSE。

文法:

string strrchr ( string string, string needle )

該函數行為同 strstr() 函數,參數意義可參見上面 strstr() 函數參數說明。

例子:

<?php$str="AAA|BBB|CCC";echo strrchr($str, "|");?>

運行例子,輸出:

|CCC

結合 substr() 函數便可以實現 截取某個最後出現的字元後面的所有內容 這一功能:

<?php$str="AAA|BBB|CCC";echo substr(strrchr($str, "|"), 1);?>

聯繫我們

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