strpos() 函数是 PHP 中用于查找字符串中第一次出现指定文本位置的内置函数。它返回指定文本在字符串中第一次出现的索引值,也就是从 0 开始计算的位置,如果未找到指定文本则返回 false。
strpos() 函数有三个参数:
$haystack:必需,要搜索的目标字符串。
$needle:必需,要查找的字符串或字符。
$offset:可选,指定该函数从目标字符串的哪个位置开始查找,默认值为 0。
strpos() 函数返回的是整数(包括 0),表示查找到的子串在目标字符串中的位置,如果没有找到,则返回 false。
strpos() 函数语法如下:
strpos(string,find,start)
参数说明:
string:必选,要查找的原始字符串。
find:必选,要查找的字符串。可以是一个字符或多个字符组成的子串。
start:可选,规定从哪个位置开始搜索。默认是 0。
例如,以下代码可以查找字符串 “Hello World!” 中的字母 “o” 并返回其所在位置:
<?php
$mystring = 'Hello World!';
$findme = 'o';
$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 'o' was found in the string 'Hello World!' and exists at position 4
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END