Чтобы проверить, существует ли слово в строке с помощью PHP, вы можете использовать несколько методов. Вот несколько примеров:
Метод 1: strpos()
$string = "This is a sample string";
$word = "sample";
if (strpos($string, $word) !== false) {
echo "Word found in string";
} else {
echo "Word not found in string";
}
Метод 2: preg_match()
$string = "This is a sample string";
$word = "sample";
if (preg_match("/\b" . preg_quote($word, "/") . "\b/i", $string)) {
echo "Word found in string";
} else {
echo "Word not found in string";
}
Метод 3: strstr()
$string = "This is a sample string";
$word = "sample";
if (strstr($string, $word)) {
echo "Word found in string";
} else {
echo "Word not found in string";
}
Метод 4: взорвать() и in_array()
$string = "This is a sample string";
$word = "sample";
$words = explode(" ", $string);
if (in_array($word, $words)) {
echo "Word found in string";
} else {
echo "Word not found in string";
}
Метод 5: str_word_count()
$string = "This is a sample string";
$word = "sample";
$wordCount = str_word_count($string, 1);
if (in_array($word, $wordCount)) {
echo "Word found in string";
} else {
echo "Word not found in string";
}
Это всего лишь несколько примеров того, как можно проверить, существует ли слово в строке, с помощью PHP. В зависимости от ваших конкретных потребностей и требований один метод может подойти больше, чем другие.