曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 2758|回复: 0
打印 上一主题 下一主题

strpos() -- 找到子串第一次出现的位置

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2011-12-15 14:59:22 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
函数声明:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
该函数从 $haystack 中查找 $needle ,如果找到则返回第一次匹配所在的位置。


测试代码
[PHP] 纯文本查看 复制代码
<?php
$mystring = 'www.groad.net';
$findme   = 'groad';
$pos = strpos($mystring, $findme);

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

运行输出:
The string 'groad' was found in the string 'www.groad.net' and exists at position 4
上面的位置是从 0 开始算起。

函数可以指定第 3 个参数,该参数指定从第几个字符开始查找,比如:
[PHP] 纯文本查看 复制代码
<?php                                                                                                                                                                 
$mystring = 'abcdef abcdef';                                                                                                                                          
$findme   = 'a';                                                                                                                                                      
$pos = strpos($mystring, $findme, 3);                                                                                                                                 

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

运行输出:
The string 'a' was found in the string 'abcdef abcdef' and exists at position 7
这时候的位置是 7 。如果不指定第 3 个参数,那么第一个字符就发生了匹配,所以位置会是 0 。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-6 10:20 , Processed in 0.081358 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表