php查找字符串首次出现的位置 判断字符串是否在另一个字符串中

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

说明

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

返回 needle 在 haystack 中首次出现的数字位置。与 strrpos() 不同,在 PHP 5 之前,该函数可以使用一个完整字符串作为 needle,并且整个字符串都将被使用。

参数

 

haystack

在该字符串中进行查找。

needle

如果 needle 不是一个字符串,那么它将被转换为整型并被视为字符的顺序值。

offset

可选的 offset 参数可以用来指定从 haystack 中的哪一个字符开始查找。返回的数字位置是相对于 haystack 的起始位置而言的。

 

返回值

以整型返回位置信息。如果没找到 needlestrpos() 将返回布尔型的 FALSE 值。

Warning

此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值,例如 0 或 ""(空串)。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符 来测试此函数的返回值。

范例

 

Example #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";
}
?>

Example #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'";
}
?>

Example #3 使用位置偏移量

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

 

注释

Note此函数可安全用于二进制对象。

参见

 

    • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
    • stripos() - 查找字符串首次出现的位置(不区分大小写)
    • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置(不区分大小写)
    • strrchr() - 查找指定字符在字符串中的最后一次出现
    • substr() - 返回字符串的子串
    • stristr() - strstr 函数的忽略大小写版本
    • strstr() - 查找字符串的首次出现
posted @   虚幻的街景  阅读(25444)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示