php strpos()函数是用于查找字符串中第一次出现另一个字符串的位置。它可以在字符串中快速搜索指定的字符串,并返回它找到的位置。如果没有找到,则返回FALSE。
使用方法
strpos()函数的语法如下:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
参数说明:
- haystack:必需。规定要搜索的字符串。
- needle:必需。规定要查找的字符串。
- offset:可选。规定在 haystack 中开始搜索的位置。
下面是一个实例:
$mystring = 'abc'; $findme = 'a'; $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 'a' was found in the string 'abc' and exists at position 0。
strpos()函数还可以用于检查字符串是否存在,例如:
if (strpos($mystring, $findme) !== false) { echo "The string '$findme' was found in the string '$mystring'"; }
上面代码的输出结果是:The string 'a' was found in the string 'abc'。
strpos()函数也可以用于查找多个字符串,例如:
$mystring = 'abc'; $findme = array('a', 'b', 'c'); foreach ($findme as $value) { if (strpos($mystring, $value) !== false) { echo "The string '$value' was found in the string '$mystring'"; } }
上面代码的输出结果是:The string 'a' was found in the string 'abc'The string 'b' was found in the string 'abc'The string 'c' was found in the string 'abc'。