What is the best way to check if a word from a database is present in a string in PHP?
To check if a word from a database is present in a string in PHP, you can fetch the word from the database and then use the `strpos()` function to check if it exists in the string. The `strpos()` function returns the position of the first occurrence of a substring in a string, or `false` if the substring is not found.
// Fetch word from database
$word = "example";
// String to check
$string = "This is an example sentence.";
// Check if word is present in the string
if(strpos($string, $word) !== false) {
echo "Word found in string.";
} else {
echo "Word not found in string.";
}
Related Questions
- What is the difference between accessing a static property and an instance property in PHP classes?
- What are the best practices for handling database queries and outputting data in PHP to avoid errors like unexpected syntax errors?
- How can errors related to echoing variables in PHP scripts without parentheses be resolved?