函数声明: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 。 |