哈希空间 Ctrl + F 进行搜索
首页 php手册中文版 CSS中文手册 哈希文档 Markdown在线工具

strpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strpos查找字符串首次出现的位置

说明

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

返回 needlehaystack 中首次出现的数字位置。

参数

haystack

在该字符串中进行查找。

needle

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。

返回值

返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始,而不是从1开始的。

如果没找到 needle,将返回 false

警告

此函数可能返回布尔值 false,但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 说明
8.0.0 不再支持 int 传入 needle
7.3.0 弃用 int 传入 needle
7.1.0 开始支持负数的 offset

范例

示例 #1 使用 ===

<?php
$mystring 
'abc';
$findme   'a';
$pos strpos($mystring$findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作,
// 因为 'a' 是第 0 位置上的(第一个)字符。
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 使用 !==

<?php
$mystring 
'abc';
$findme   'a';
$pos strpos($mystring$findme);

// 使用 !== 操作符。使用 != 不能像我们期待的那样工作,
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 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 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring 'abcdef abcdef';
$pos strpos($newstring'a'1); // $pos = 7, 不是 0
?>

注释

注意: 此函数可安全用于二进制对象。

参见

打开 哈希空间 微信小程序中查看更佳