Функция PHP strposиспользуется для поиска позиции первого вхождения подстроки в строку. Вот несколько методов, которые можно использовать для достижения этой цели, а также примеры кода:
Метод 1: использование strpos
$haystack = "Hello, world!";
$needle = "world";
$position = strpos($haystack, $needle);
if ($position !== false) {
echo "The substring '$needle' was found at position $position.";
} else {
echo "The substring '$needle' was not found.";
}
Метод 2: использование stripos(поиск без учета регистра)
$haystack = "Hello, world!";
$needle = "WORLD";
$position = stripos($haystack, $needle);
if ($position !== false) {
echo "The substring '$needle' (case-insensitive) was found at position $position.";
} else {
echo "The substring '$needle' (case-insensitive) was not found.";
}
Метод 3: использование strstr(возвращает подстроку, начиная с первого вхождения)
$haystack = "Hello, world!";
$needle = "world";
$substring = strstr($haystack, $needle);
if ($substring !== false) {
echo "The substring '$needle' was found. The remaining string is '$substring'.";
} else {
echo "The substring '$needle' was not found.";
}
Метод 4: использование strchr(аналогично strstr, но возвращает подстроку, начиная с первого вхождения)
$haystack = "Hello, world!";
$needle = "world";
$substring = strchr($haystack, $needle);
if ($substring !== false) {
echo "The substring '$needle' was found. The remaining string is '$substring'.";
} else {
echo "The substring '$needle' was not found.";
}