Tags
Asked 2 years ago
17 Jun 2021
Views 211
Beatrice

Beatrice posted

How do I check if a string contains a specific word?

How do I check if a string contains a specific word?
sec8

sec8
answered Apr 27 '23 00:00

In PHP, you can check if a string contains a specific word by using the strpos () function. The strpos () function returns the position of the first occurrence of a substring in a string, or false if the substring is not found. Here's an example:



$string = "The quick brown fox jumps over the lazy dog";
$word = "fox";

if (strpos($string, $word) !== false) {
    echo "The string contains the word '$word'";
} else {
    echo "The string does not contain the word '$word'";
}

In this example, we use the strpos () function to check if the string $string contains the word "fox". If the word is found, the condition strpos ($string, $word ) !== false evaluates to true, and we print the message "The string contains the word 'fox'". If the word is not found, the condition evaluates to false, and we print the message "The string does not contain the word 'fox'".

Note that the strpos() function is case-sensitive. If you want to check for a word regardless of its case, you can convert both the string and the word to lowercase or uppercase before calling the strpos() function. For example:

php
Copy code
$string = "The quick brown fox jumps over the lazy dog";
$word = "FOX";

if (strpos(strtolower($string), strtolower($word)) !== false) {
echo "The string contains the word '$word'";
} else {
echo "The string does not contain the word '$word'";
}
In this example, we convert both the string and the word to lowercase using the strtolower() function before calling the strpos() function. This ensures that the function will find the word regardless of its case.
Post Answer