PHP中如何使用strpos函数查找子串在字符串中 次出现的位置?
发布时间:2023-06-06 03:47:31
在PHP中,strpos函数是一个非常常用的字符串处理函数,用于查找一个子串(needle)在另一个字符串(haystack)中 次出现的位置。
该函数的语法如下:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
其中,$haystack参数是要查找的主字符串,$needle参数是要查找的子字符串,$offset参数是查找的起始位置,可以省略,默认值为0。
如果查找不到子串,则该函数返回false;如果查找成功,则返回子串在主字符串中 次出现的位置,位置以0开始计数。
下面是一个例子:
$str = "hello world";
$pos = strpos($str, "world");
if ($pos === false) {
echo "Not found";
} else {
echo "Found at position " . $pos;
}
输出结果为:
Found at position 6
此时,$pos的值为6,表示子串“world”在主字符串“hello world”中 次出现的位置。需要注意的是,$pos的值可能为0,但这并不代表子串在主串的 个位置出现,而是表示它出现在第0个位置。
如果要查找子串出现的所有位置,可以使用strpos函数的变体函数stripos(),该函数不区分大小写,可以在主串中查找子串的所有位置。
$str = "hello World, world is beautiful";
$pos = stripos($str, "world");
while ($pos !== false) {
echo "Found at position " . $pos . "<br>";
$pos = stripos($str, "world", $pos + 1);
}
输出结果为:
Found at position 6 Found at position 14
此时,$pos的值分别为6和14,表示子串“world”在主字符串“hello World, world is beautiful”中出现了两次。这里需要注意的是,我们使用了一个while循环来不断查找子串在主串中的下一个位置,直到无法查找为止。
