There are multiple ways to check if a string contains any words from the given array using PHP. You can check one specific word or multiple words from an array.
Check if a string contains a specific word:
Use the PHP str_contains() function to determine if a string contains a specific word.
<?php
$string = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry area.';
$word = 'dummy';
// Case sensitive
if (str_contains($string, $word)) {
echo "String contains '$word'";
} else {
echo "String does not contains '$word'";
}
// Case insensitive
if (stripos($string, $word) !== false) {
echo "String contains '$word'";
} else {
echo "String does not contains '$word'";
}
?>
php
Check if a string contains multiple specific words:
If you want to check multiple words in a string, define words in an array. The following code snippets can help to check whether a string contains any words from the given array using PHP.
<?php
$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry area.";
$words = ["ipsum", "text", "area"];
// Using str_contains (PHP 8+)
foreach ($words as $word) {
if (str_contains($string, $word)) {
echo "String contains '$word'\n";
}
}
// Using stripos (case-insensitive)
foreach ($words as $word) {
if (stripos($string, $word) !== false) {
echo "String contains '$word'\n";
}
}
// Using preg_match (case-insensitive)
$pattern = '/\b(' . implode('|', array_map('preg_quote', $words)) . ')\b/i';
if (preg_match($pattern, $string, $matches)) {
echo "String contains a word from the array: " . implode(", ", array_unique($matches)) . "\n";
}
?>
Custom function to check if a string contains specific words from an array and return a boolean value (true/false) using PHP:
function stringContainsWords(string $string, array $words): bool
{
foreach ($words as $word) {
if (stripos($string, $word) !== false) {
return true; // If any word is found, return true immediately
}
}
return false; // Words were not found
}
Top comments (0)