strpos
(PHP 4, PHP 5, PHP 7, PHP 8)
strpos — 查找字符串首次出现的位置
说明
返回 needle 在 haystack 中首次出现的数字位置。
参数
haystack-
在该字符串中进行查找。
needle-
要搜索的字符串。
Prior to PHP 8.0.0, if
needleis 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, theneedleshould either be explicitly cast to string, or an explicit call to chr() should be performed. offset-
如果提供了此参数,搜索会从字符串该字符数的起始位置开始统计。 如果是负数,搜索会从字符串结尾指定字符数开始。
错误/异常
-
如果
offset大于haystack的长度,则会抛出 ValueError 异常。
更新日志
| 版本 | 说明 |
|---|---|
| 8.0.0 |
needle 现在接受空字符串。
|
| 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
echo $pos, PHP_EOL;
?>注释
注意: 此函数可安全用于二进制对象。
参见
- stripos() - 查找字符串首次出现的位置(不区分大小写)
- str_contains() - 确定字符串是否包含指定子串
- str_ends_with() - 检查字符串是否以指定子串结尾
- str_starts_with() - 检查字符串是否以指定子串开头
- strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
- strripos() - 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
- strstr() - 查找字符串的首次出现
- strpbrk() - 在字符串中查找一组字符的任何一个字符
- substr() - 返回字符串的子串
- preg_match() - 执行匹配正则表达式