PHP字符串函數之 strstr stristr strchr strrchr

PHP字符串函數之 strstr stristr strchr strrchr


  • strstr – 查找字符串的首次出現,返回字符串從第一次出現的位置開始到該字符串的結尾或開始。
  • stristr – strstr 函數的忽略大小寫版本
  • strchr – strstr 函數的別名
  • strrchr – 查找字符串的最後一次出現,返回字符串從最後一次出現的位置開始到該字符串的結尾。

strstr

查找字符串的首次出現,返回字符串從第一次出現的位置開始到該字符串的結尾或開始。

mixed strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

參數說明

haystack
在該字符串中進行查找。
needle
如果 needle 不是一個字符串,那麼它將被轉換爲整型並被視爲字符的順序值來使用。
before_needle
若爲 TRUE,strstr() 將返回 needle 在 haystack 中的位置之前的部分。

返回值

成功:返回字符串 needle 之前或之後的一部分
失敗:如果沒找到 needle,將返回 FALSE。

注意

  1. 該函數區分大小寫
  2. 如果你僅僅想確定 needle 是否存在於 haystack 中,請使用速度更快、耗費內存更少的 strpos() 函數

示例

<?php
/*【 needle 爲單個字符 】 */
$email  = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com

$user = strstr($email, '@', true); // 從 PHP 5.3.0 起
echo $user; // 打印 name
?>
<?php
/*【 needle 爲數字 】 */
$email  = '[email protected]'; //字母a的 ASCII碼爲 97
$behind = strstr($email, 97);
echo $behind; // 打印 [email protected]

$front = strstr($email, 97, true); // 從 PHP 5.3.0 起
echo $front; // 打印 n
?>
<?php
/*【 needle 爲字符串 】 */
$email = '[email protected]';
$behind  = strstr($email, 'ex');
echo $behind; // 打印 example.com

$front = strstr($email, 'ex', true); // 從 PHP 5.3.0 起
echo $front; // 打印 name@
*/
?>
<?php
/*【 needle 爲字符串 】 */
$email = '[email protected]';
$behind  = strstr($email, 'ab');
echo $behind; // 返回 false

$front = strstr($email, 'ab', true); // 從 PHP 5.3.0 起
echo $front; // 返回 false
*/
?>

stristr

strstr() 函數的忽略大小寫版本

mixed stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

該函數與 strstr() 唯一的區別就是不區分大小寫。其他可參考strstr()

<?php
$email  = '[email protected]';
$behind = stristr($email, 'A');
echo $behind; // 打印 [email protected]

$front = stristr($email, 'A', true); // 從 PHP 5.3.0 起
echo $front; // 打印 n
?>

strchr

strstr() 函數的別名

mixed strchr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

該函數等同 strstr() 。其他可參考strstr()

$email  = '[email protected]';
$behind = strchr($email, 'a');
echo $behind; // 打印 [email protected]

$front = strchr($email, 'a', true); // 從 PHP 5.3.0 起
echo $front; // 打印 n
?>

strrchr

查找字符串的最後一次出現,返回字符串從最後一次出現的位置開始到該字符串的結尾。

mixed strrchr ( string $haystack , mixed $needle )

參數說明

haystack
在該字符串中進行查找。
needle
如果 needle 包含了不止一個字符,那麼僅使用第一個字符。該行爲不同於 strstr()
如果 needle 不是一個字符串,那麼將被轉化爲整型並被視爲字符順序值。

返回值

成功:返回字符串 needle 之後的一部分
失敗:如果沒找到 needle,將返回 FALSE。

示例

<?php
/*【 needle 爲字符 】 */
$email  = '[email protected]';
$behind = strrchr($email, 'a');
echo $behind; // 打印 ample.com
?>
/*【 needle 爲字符串 】 */
$email  = '[email protected]';
$behind = strrchr($email, 'am');
echo $behind; // 打印 ample.com
?>
<?php
/*【 needle 爲數字 】 */
$email  = '[email protected]';
$behind = strrchr($email, 97);
echo $behind; // 打印 ample.com
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章