PHP 字符串獲取 substr 與 strstr 函數
PHP 字符串獲取
用於從字符串中獲取指定字符串。
相關函數如下:
- substr():從字符串中獲取其中的一部分
- strstr():查找字符串在另一個字符串中第一次出現的位置,並返回從該位置到字符串結尾的所有字符
- subchr():同 strstr()
- strrchr():查找字符串在另一個字符串中最后一次出現的位置,並返回從該位置到字符串結尾的所有字符
substr()
substr() 函數用於從字符串中獲取其中的一部分,返回一個字符串。
語法:
string substr ( string string, int start [, int length] )
參數 | 說明 |
---|---|
string | 要處理的字符串 |
start | 字符串開始位置,起始位置為 0 ,為負則從字符串結尾的指定位置開始 |
length | 可選,字符串返回的長度,默認是直到字符串的結尾,為負則從字符串末端返回 |
例子:
<?php echo substr('abcdef', 1); //輸出 bcdef echo substr('abcdef', 1, 2); //輸出 bc echo substr('abcdef', -3, 2); //輸出 de echo substr('abcdef', 1, -2); //輸出 bcd ?>
提示
如果 start 是負數且 length 小於等於 start ,則 length 為 0。
strstr()
查找字符串在另一個字符串中第一次出現的位置,並返回從該位置到字符串結尾的所有字符,如果沒找到則返回 FALSE。
語法:
string strstr ( string string, string needle )
參數 | 說明 |
---|---|
string | 要處理的字符串 |
needle | 要查找的字符串,如果是數字,則搜索匹配數字 ASCII 值的字符 |
例子:
<?php $email = 'user@5idev.com'; $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); ?>