當前位置: 首頁> 最新文章列表> 如何使用stristr 函數進行不區分大小寫的字符串查找

如何使用stristr 函數進行不區分大小寫的字符串查找

gitbox 2025-05-29

一、什麼是stristr()

stristr()是PHP 的一個內置函數,用於在一個字符串中搜索另一個字符串(不區分大小寫),並返回從匹配點開始的子字符串。

函數定義:

 stristr(string $haystack, mixed $needle, bool $before_needle = false): string|false

參數說明:

  • $haystack :被搜索的主字符串。

  • $needle :要查找的子字符串。

  • $before_needle (可選):如果為true ,函數返回主字符串中從起始位置到needle 第一次出現之前的部分。


二、基本用法示例

1. 查找並返回匹配子串之後的內容

<?php
$text = "Welcome to GitBox.net!";
$result = stristr($text, "gitbox");
echo $result;
?>

輸出:

 GitBox.net!

說明:不論大小寫, stristr()成功找到了"gitbox",並返回從該位置到字符串末尾的所有內容。


2. 使用$before_needle參數獲取匹配之前的部分

<?php
$text = "Learn PHP at GitBox.net for free.";
$result = stristr($text, "gitbox", true);
echo $result;
?>

輸出:

 Learn PHP at 

說明:設置第三個參數為true後,返回的是"gitbox" 之前的部分。


三、與strstr()的區別

stristr()strstr()的不區分大小寫版本。 strstr()區分大小寫,而stristr()忽略大小寫。

示例比較:

 <?php
$text = "GitBox.net Official Site";

// 區分大小寫查找
$result1 = strstr($text, "gitbox");
var_dump($result1); // bool(false)

// 不區分大小寫查找
$result2 = stristr($text, "gitbox");
var_dump($result2); // string(14) "GitBox.net Official Site"
?>

四、結合其他函數使用的技巧

1. 判斷是否包含子字符串

你可以通過判斷stristr()返回值是否為false來判斷是否包含目標字符串:

 <?php
$url = "https://www.gitbox.net/page";
if (stristr($url, "gitbox")) {
    echo "URL 包含 'gitbox'";
} else {
    echo "URL 不包含 'gitbox'";
}
?>

2. 在數組中過濾包含某關鍵詞的字符串

<?php
$data = ["Welcome to GitBox.net", "Visit example.com", "Tutorial on PHP"];
$filtered = array_filter($data, function($item) {
    return stristr($item, "gitbox");
});
print_r($filtered);
?>

輸出:

 Array
(
    [0] => Welcome to GitBox.net
)

五、注意事項

  • stristr()返回的是字符串或false ,所以在使用時需要特別注意對false的判斷,避免將其當作字符串處理。

  • 如果目標字符串中含有非英文字符, stristr()依然有效,但需確保字符集一致或使用多字節函數進行處理。