stristr 是 PHP 中的一個字符串搜索函數,它從給定的字符串中查找首次出現的子字符串
function stristr($haystack, $needle) {
if ($needle === '') {
return $haystack;
}
$pos = strpos($haystack, $needle);
if ($pos === false) {
return '';
} else {
return substr($haystack, $pos);
}
}
在這個函數中,我們首先檢查 $needle 是否為空字符串。如果是空字符串,我們直接返回整個 $haystack,因為從空字符串中找不到任何子字符串。
接下來,我們使用 strpos 函數查找 $haystack 中首次出現的 $needle 的位置。如果找到了(即 $pos 不為 false),我們使用 substr 函數從 $haystack 中提取子字符串,從 $pos 開始到原字符串末尾。如果沒有找到(即 $pos 為 false),我們返回一個空字符串。
這樣,我們可以處理 stristr 函數可能產生的錯誤情況,例如當 $needle 為空字符串時,或者當 $haystack 中不存在 $needle 時。