In PHP development, we often need to judge whether a paragraph of text contains certain keywords. This requirement is very common in content review, automatic tag classification, and simple search functions. PHP provides very practical string processing functions, among which stripos() is a powerful tool. With foreach , we can easily achieve matching judgments for multiple keywords.
stripos() is a built-in function in PHP to find where a string first appears in another string. Unlike strpos() , strpos() is case-insensitive. If found, the index of that location is returned; if not found, false is returned.
The syntax is as follows:
stripos(string $haystack, string $needle): int|false
$haystack : The target string to search for
$needle : the keyword to look for
We can put multiple keywords into an array, and then use foreach to loop through each keyword, and use stripos() to determine whether the target text contains these words.
Here is a complete example code:
<?php
$text = "Welcome to our website,For more technical tutorials, please go https://m66.net。";
$keywords = ["Tutorial", "PHP", "study", "technology"];
$foundKeywords = [];
foreach ($keywords as $keyword) {
if (stripos($text, $keyword) !== false) {
$foundKeywords[] = $keyword;
}
}
if (!empty($foundKeywords)) {
echo "Find the following keywords:\n";
echo implode(", ", $foundKeywords);
} else {
echo "No keywords found。";
}
Find the following keywords:
Tutorial, technology
In this example, the program successfully detected the existence of two keywords "tutorial" and "technology" in the text. In this way, you can quickly analyze what keywords you are interested in in a paragraph of text.
Since stripos() searches for matches throughout the text, sometimes some words containing keyword fragments may be misjudged. Therefore, if you want to match keywords more accurately (such as matching only the entire word), you can handle it in combination with the regular expression preg_match() . But if it is just a rough filter, stripos() is practical and efficient enough.
Using stripos() with foreach is a concise solution to determine whether the text contains multiple keywords. This method is both simple and easy to understand and has high performance, and is suitable for most basic application scenarios. Hope this article will be helpful to you in actual development!