PHP中的strpos()函数示例-在字符串中查找子字符串
发布时间:2023-10-03 20:06:55
在PHP中,strpos()函数用于在字符串中查找指定子字符串的 次出现的位置。
函数原型:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
具体用法如下:
1. 查找子字符串的 次出现的位置:
$string = 'Hello World'; $pos = strpos($string, 'World'); echo $pos; // 输出 6
在上述示例中,strpos()函数在字符串$string中查找'World'子字符串的位置,并返回其 次出现的索引。由于'World'在字符串中的索引位置是6,所以输出的结果为6。
2. 查找子字符串的 次出现的位置,指定起始偏移量:
$string = 'Hello World Hello'; $pos = strpos($string, 'Hello', 7); echo $pos; // 输出 12
在上述示例中,strpos()函数在字符串$string中查找'Hello'子字符串的位置,并指定起始偏移量为7。由于起始偏移量7之前的字符包含了 个'Hello',所以返回的结果是12。
3. 查找子字符串的 次出现的位置,区分大小写:
$string = 'Hello World'; $pos = strpos($string, 'world'); echo $pos; // 输出 false $string = 'Hello World'; $pos = strpos($string, 'World'); echo $pos; // 输出 6
在上述示例中, 个调用strpos()函数时,由于查找'world'子字符串时没有找到,所以返回false。而第二个调用strpos()函数时,查找'World'子字符串找到,并返回其 次出现的索引位置6。
4. 查找子字符串的 次出现的位置,返回bool值:
$string = 'Hello World'; $pos = strpos($string, 'World', 6); var_dump($pos); // 输出 bool(true)
在上述示例中,由于调用strpos()函数时指定起始偏移量为6,而'World'子字符串在索引位置6后仍然存在,所以返回的结果是bool值true。
需要注意的是,如果子字符串未找到,则返回false。同时,由于strpos()函数返回的是子字符串 次出现的索引位置,所以如果子字符串是位于字符串开始部分,返回的结果是0。
