在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()
函數將它們轉換為全小寫或全大寫。