stristr 函数是 PHP 中的一个字符串查找函数,它是 strstr 函数的忽略大小写版本。stristr 用于在字符串中查找子字符串,并返回子字符串在原字符串中第一次出现的位置及其后面的所有内容。如果未找到子字符串,返回 false

函数原型

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

参数说明

  • $haystack:要搜索的字符串。

  • $needle:要搜索的子字符串。如果 $needle 不是一个字符串,它将被转换为整数并被视为字符顺序值。

  • $before_needle:可选参数,布尔值。如果设置为 true,则返回 $needle 在 $haystack 中第一次出现的位置之前的部分(不包括 $needle)。

返回值

  • 返回匹配的子字符串。如果 $needle 未找到,返回 false

示例

1.基本用法

$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e'); // 输出 ER@EXAMPLE.com
echo stristr($email, 'e', true); // 输出 US

2.测试字符串的存在与否

$string = 'Hello World!';
if (stristr($string, 'earth') === false) {
    echo '"earth" not found in string';
}
// 输出: "earth" not found in string
//这里,stristr 函数检查 'earth' 是否存在于 $string 中。如果未找到,输出相应的消息。

3.使用非字符串 $needle

$string = 'APPLE';
echo stristr($string, 97); // 97 = 小写字母 'a'
// 输出: APPLE

这里,97 是小写字母 'a' 的 ASCII 值。stristr 函数在 $string 中查找字符 'a',并返回第一次出现的位置及其后面的所有内容。

需要注意的是

  • 大小写敏感stristr 函数是不区分大小写的。如果需要进行区分大小写的搜索,应使用 strstr 函数。

  • 参数类型:从 PHP 8.0.0 开始,$needle 不再支持整数类型。如果需要使用整数,应将其显式转换为字符串。

参考:

  • strstr():查找字符串的首次出现,区分大小写。