當前位置: 首頁> 最新文章列表> 深入解析PHP中stristr()函數的用法與示例

深入解析PHP中stristr()函數的用法與示例

M66 2025-06-24

PHP中的stristr()函數詳解

stristr() 函數用於在一個字符串中搜索另一個字符串第一次出現的位置,且搜索時不區分大小寫。

函數語法

<span class="fun">stristr(str, search, before_search)</span>

參數說明

  • str - 要搜索的目標字符串。

  • search - 需要查找的字符串。

  • before_search - 布爾值,默認是false 。若設置為true ,函數返回的是第一次出現search之前的字符串部分。

返回值

該函數返回從首次匹配到的字符串開始直到字符串結尾的部分,或者當before_searchtrue時,返回匹配字符串之前的內容。如果未找到匹配,則返回false

示例演示

下面的代碼示例展示瞭如何使用stristr()函數:

 <?php
$mystr = 'Tom Hanks!';
if (stristr($mystr, 'Tim') === FALSE) {
    echo 'Tim is not in the string!';
}
?>

輸出結果

<span class="fun">Tim is not in the string!</span>

另一個示例:返回匹配之前的字符串部分

<?php
echo stristr("Demo text!", "TEXT", true);
?>

輸出結果

<span class="fun">Demo</span>

通過以上示例可以看到,stristr() 函數靈活且方便,適用於需要忽略大小寫進行字符串查找的場景。