实例
查找 php 在字符串中第一次出现的位置:
<?php
echo strpos("i love php, i love php too!","php")
;?>
定义和用法
strpos() f函数查找字符串在另一字符串中第一次出现的位置(区分大小写)。
注释:strpos() 函数是区分大小写的。
注释:该函数是二进制安全的。
相关函数:
strrpos() - 查找字符串在另一字符串中最后一次出现的位置(区分大小写)
stripos() - 查找字符串在另一字符串中第一次出现的位置(不区分大小写)
strripos() -查找字符串在另一字符串中最后一次出现的位置(不区分大小写)
语法
strpos(string,find,start)
参数 描述
string 必需。规定被搜索的字符串。
find 必需。规定要查找的字符。
start 可选。规定开始搜索的位置。
技术细节
返回值: 返回字符串在另一字符串中第一次出现的位置,如果没有找到字符串则返回 false。注释: 字符串位置从 0 开始,不是从 1 开始。
php 版本: 4+
strpos()函数的返回值问题,如果没有找到会返回false,假如子字符串一开始就出现,那么会返回0。为了区分返回的0与false,必须使用同等操作符 === 或 !==。
01 <?php
02 $mystring = 'abcde';
03 $findme = 'ab';
04 $pos = strpos($mystring, $findme);
05
06 // note our use of ===. simply == would not work as expected
07 // because the position of 'ab' was the 0th (first) character.
08 // 这里使用了恒等于 ===,如果使用 == 的话无法得到预期的结果
09 // 因为字符串 ab 是从第0个字符开始的
10 if ($pos === false)
11 {
12 echo "the string '$findme' was not found in the string '$mystring'";
13 }
14 else
15 {
16 echo "the string '$findme' was found in the string '$mystring'";
17 echo " and exists at position $pos";
18 }
19 ?>
程序输出:
the string 'ab' was found in the string 'abcde' and exists at position 0
以上就是php查找字符串在另一字符串中第一次出现的位置(区分大小写)的函数strpos() 的详细内容。