PHP中查找字符串strpos和strstr有什么区别

php 2023-06-07 318次浏览

前言

在日常项目和需求的开发中,免不了要做一些字符串查找相关的操作,在 PHP 中,strpos()strstr() 函数都可以用来查找字符串中的子串,但它们也有一些区别。

1. strpos

strpos() 函数返回子串在字符串中第一次出现的位置,如果子串不存在,则返回 false
其语法如下:

strpos(string $haystack, mixed $needle, int $offset = 0): int|false

其中,$haystack 表示要查找的字符串,$needle 表示要查找的子串,$offset 表示查找的起始位置,默认为 0。

例如,要在字符串中查找子串 code

$str = "ngxcode.com";
$pos = strpos($str, "code");
if ($pos !== false) {
    echo "子串 'code' 在字符串中的位置为:$pos";
} else {
    echo "子串 'code' 不存在";
}

输出结果为:

子串 'code' 在字符串中的位置为:3

2. strstr

strstr() 函数返回子串在字符串中第一次出现的位置及其后面的所有字符,如果子串不存在,则返回 false
其语法如下:

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

其中,$haystack 表示要查找的字符串,$needle 表示要查找的子串,$before_needle 表示是否返回子串之前的字符,默认为 false

例如,要在字符串中查找子串 code

$str = "ngxcode.com";
$pos = strstr($str, "code");
if ($pos !== false) {
    echo "子串 'code' 在字符串中的位置为:$pos";
} else {
    echo "子串 'code' 不存在";
}

输出结果为:

子串 'world' 在字符串中的位置为:code.com

结语

以上就是PHP中查找字符串strposstrstr函数使用的一些简单介绍和区别,更多文章请关注本站其他内容,感谢!

PHP中查找字符串strpos和strstr有什么区别

喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址