In PHP, we often need to determine whether a string contains another specific word or substring. This kind of operation is very common in scenarios such as processing user input, filtering keywords, and building search functions. PHP provides a very practical function - stripos() , which can help us easily accomplish this task.
stripos() is a string function in PHP that finds where a substring first appears in the target string. Its biggest feature is that it is case-insensitive , which is very convenient in practical applications.
int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
$haystack : The target string to search for.
$needle : The substring to be found.
$offset : (Optional) Start a search from somewhere in the target string.
If a substring is found, stripos() returns its position in the target string (starting from 0), otherwise returns false .
Let’s look at a simple example to determine whether a paragraph contains the word “PHP”:
$text = "Welcome to our website:https://www.m66.net,We focus onPHPDevelopment!";
if (stripos($text, "php") !== false) {
echo "Included in the text PHP!";
} else {
echo "Not included in the text PHP。";
}
Included in the text PHP!
Note that !== false is used here, instead of == true , because scripos() returns the position (such as position 0). If (stripos(...)) is used directly, there will be a problem of errors in judgment.
Keyword filtering :
$badWords = ['spam', 'advertise', 'Sensitive words'];
$userInput = "This link https://www.m66.net 是一个advertise网站。";
foreach ($badWords as $word) {
if (stripos($userInput, $word) !== false) {
echo "检测到Sensitive words:$word\n";
}
}
Search prompt function :
Suppose you are building a search function that needs to check whether the keywords entered by the user match certain article titles:
$keyword = "Tutorial";
$titles = [
"PHP 基础入门Tutorial",
"JavaScript Study Guide",
"Python Data Analysis",
];
foreach ($titles as $title) {
if (stripos($title, $keyword) !== false) {
echo "Find the relevant title:$title\n";
}
}
stripos() is a very useful string function in PHP, suitable for case-insensitive string matching scenarios. It can be used in multiple practical development scenarios such as keyword filtering, search function, and data verification. As long as you master its return value characteristics and use !== false to make judgments, you can efficiently determine whether the string contains a specific word.
Mastering this function can make your PHP string processing more flexible and efficient!