php strpos()函数查找字符串中第一次出现另一个字符串的位置

分类:知识百科 日期: 点击:0

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'。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。