PHP中strpos、strstr和stripos、stristr函数分析

发布时间:2026-10-03 04:01:18 浏览次数:4

PHP中strpos、strstr和stripos、stristr函数分析

什么是strpos函数和strstr函数?

  • strpos 函数:查找字符串首次出现的位置。
  • strstr 函数:查找字符串在另外一个字符串中的第一次出现。

这两个函数区别在于:

  • strpos 返回的是目标字符串在原字符串中的起始位置;
  • strstr 返回的则是目标字符串之后,原字符串剩余部分,包括目标字符串本身。

strpos函数的语法

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

参数说明:

  • haystack: 要被查找的主字符串;
  • needle: 必需,规定需要在主字符串中查找的字符串/字符;
  • offset: 可选,规定在主字符串中搜索的起始位置。默认是 0。

方案一:查找一个子字符串在原字符串中首次出现的位置

$string = 'Hello World';$needle = 'World';$position = strpos($string, $needle);if ($position === false) {    echo '没有找到相关内容。';} else {    echo '子字符串在原字符串第 ' . ($position + 1) . ' 个位置。';}

方案二:查找一个字符串在另一个字符串中第一次出现

$mainString = 'The quick brown fox jumps over the lazy dog ';$subString = 'brown';$remainingString = strstr($mainString, $subString);if ($remainingString) {    echo $subString.'在'.$mainString.'中的第一个位置之后的字符串为 '.$remainingString;} else {    echo '未找到相关内容。';}

什么是stripos函数和stristr函数?

  • stripos 函数:查找字符串中第一次出现的位置(不区分大小写)。
  • stristr 函数:查找字符串在另外一个字符串中的第一次出现(不区分大小写)。

这两个函数与 strpos 和 strstr 差不多,但是它们不区分大小写。

stripos函数和stristr函数的语法

int stripos(string $haystack, mixed $needle, int $offset = 0)

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

参数说明:

  • haystack: 要被查找的主字符串;
  • needle: 必需,规定需要在主字符串中查找的字符串/字符;
  • offset: 可选,规定在主字符串中搜索的起始位置。默认是 0。
  • before_needle: 可选,如果设置为 TRUE,则 stristr() 函数返回 needle 之前的部分,否则返回 needle 之后的部分。默认是 FALSE。

方案一:查找一个子字符串在原字符串中首次出现的位置(不区分大小写)

$string = 'Hello World';$needle = 'world';$position = stripos($string, $needle);if ($position === false) {    echo '没有找到相关内容。';} else {    echo '子字符串在原字符串第 ' . ($position + 1) . ' 个位置。';}

方案二:查找一个字符串在另一个字符串中第一次出现(不区分大小写)

$mainString = 'The quick brown fox jumps over the lazy dog ';$subString = 'BRown';$remainingString = stristr($mainString, $subString);if ($remainingString) {    echo $subString.'在'.$mainString.'中的字符串为 '.$remainingString;} else {    echo '未找到相关内容。';}
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477