strstr 是 PHP 中的一个字符串查找函数,用于在字符串中查找子字符串。如果找到子字符串,strstr 函数会返回子字符串在原字符串中第一次出现的位置及其后面的所有内容。如果没有找到子字符串,strstr 函数会返回 false

函数原型

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

参数说明

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

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

  • $before_needle:可选参数,布尔值。如果设置为 true,则返回子字符串之前的所有内容(包括子字符串本身)。默认值为 false

返回值

  • 如果 $needle 在 $haystack 中找到,返回子字符串在 $haystack 中第一次出现的位置及其后面的所有内容。

  • 如果 $needle 未在 $haystack 中找到,返回 false

示例

  1. 基本用法

$haystack = "Hello, world!";
$needle = "world";

$result = strstr($haystack, $needle);
echo $result;  // 输出: world!

2.使用 $before_needle 参数

$haystack = "Hello, world!";
$needle = "world";

$result = strstr($haystack, $needle, true);
echo $result;  // 输出: Hello,

3.未找到子字符串

$haystack = "Hello, world!";
$needle = "foo";

$result = strstr($haystack, $needle);
var_dump($result);  // 输出: bool(false)

需要注意的是:

  • 性能问题strstr 函数在处理非常长的字符串时可能会比较慢,因为它需要遍历整个字符串来查找子字符串。

  • 大小写敏感strstr 函数是大小写敏感的。如果需要进行大小写不敏感的查找,可以先使用 strtolower 或 strtoupper 函数将字符串转换为统一的大小写,然后再进行查找

替代函数

  • strpos:返回子字符串在原字符串中第一次出现的位置(从 0 开始计数)。如果未找到子字符串,返回 false

$haystack = "Hello, world!";
$needle = "world";

$position = strpos($haystack, $needle);
if ($position !== false) {
    $result = substr($haystack, $position);
    echo $result;  // 输出: world!
}

strrpos:返回子字符串在原字符串中最后一次出现的位置(从 0 开始计数)。如果未找到子字符串,返回 false

$haystack = "Hello, world! world!";
$needle = "world";

$position = strrpos($haystack, $needle);
if ($position !== false) {
    $result = substr($haystack, $position);
    echo $result;  // 输出: world!
}

strstr 函数在 PHP 中用于查找子字符串并返回其在原字符串中第一次出现的位置及其后面的所有内容。通过使用 $before_needle 参数,可以灵活地获取子字符串之前或之后的内容。在处理字符串时,要注意性能和大小写敏感性问题,并根据需要选择合适的替代函数。