在PHP中,可以使用strpos()
和strrpos()
函数来实现字符串查找。
语法:
int strpos(string $haystack, string $needle, int $offset = 0): int
示例:
$haystack = "Hello, welcome to the world of PHP!";
$needle = "world";
$offset = 7;
$position = strpos($haystack, $needle, $offset);
if ($position !== false) {
echo "Found '$needle' at position: " . $position;
} else {
echo "'$needle' not found in the string.";
}
语法:
int strrpos(string $haystack, string $needle, int $offset = 0): int
示例:
$haystack = "Hello, welcome to the world of PHP!";
$needle = "world";
$offset = 7;
$position = strrpos($haystack, $needle, $offset);
if ($position !== false) {
echo "Found '$needle' at position: " . $position;
} else {
echo "'$needle' not found in the string.";
}
这两个函数都可以用于在字符串中查找子字符串的位置。请注意,它们对大小写敏感。如果需要进行不区分大小写的搜索,可以在传递给函数的字符串之前使用strtolower()
或strtoupper()
函数将它们转换为全小写或全大写。