首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

strpos

(PHP 4, PHP 5, PHP 7)

strpos - 查找字符串中第一次出现子字符串的位置

描述

代码语言:javascript
复制
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

查找haystack串中第一次出现针的数字位置。

参数

haystack

要搜索的字符串。

needle

如果needle不是字符串,它将转换为整数并作为字符的序数值应用。

offset

如果指定,搜索将开始从字符串开始计算的这个字符数。如果偏移量为负数,搜索将开始从字符串末尾计算的这个字符数。

返回值

返回针相对于haystack字符串开头的位置(与偏移量无关)。另请注意,字符串位置从0开始,而不是1。

如果找不到针,则返回FALSE

警告

该函数可能返回布尔值FALSE,但也可能返回一个非布尔值,其值为FALSE。有关更多信息,请阅读布尔部分。使用===运算符来测试此函数的返回值。

更新日志

描述

7.1.0

增加了对负偏移的支持。

例子

示例#1 使用 ===

代码语言:javascript
复制
<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

例#2 使用!==

代码语言:javascript
复制
<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates 
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

示例#3 使用偏移量

代码语言:javascript
复制
<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

注意

注意:此功能是二进制安全的。

扩展内容

  • stripos() - 在字符串中查找第一次出现不区分大小写的子字符串的位置
  • strrpos() - 查找字符串中最后一次出现子字符串的位置
  • strripos() - 查找字符串中不区分大小写的子字符串的最后一次出现的位置
  • strstr() - 查找第一次出现的字符串
  • strpbrk() - 在字符串中搜索任何一组字符
  • substr() - 返回字符串的一部分
  • preg_match() - 执行正则表达式匹配

← strpbrk

strrchr →

扫码关注腾讯云开发者

领取腾讯云代金券