实例
查找 "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