In PHP, the stripos() function is used to find where a string first appears in another string (case insensitive). This function is often used when processing string-related logic, such as determining whether a keyword exists in a given content.
However, due to the return value characteristic of stripos() , many developers are prone to stumble when making judgments, especially for processing the return value of 0 . This article will analyze this issue in detail and give a correct way of judgment.
$haystack = "Welcome to m66.net!";
$needle = "welcome";
$pos = stripos($haystack, $needle);
In the example above, stripos() will return 0 because "welcome" appears at the beginning of the target string (though case is different, stripos() is case-insensitive).
Many beginners will write this way:
if (stripos($haystack, $needle)) {
echo "Found the keyword";
} else {
echo "Keywords do not exist";
}
The problem with this code is that if the keyword appears at the beginning of the string (position is 0), if judgment will treat 0 as false , and the else branch is incorrectly executed .
$pos = stripos($haystack, $needle);
if ($pos !== false) {
echo "Found the keyword,Location is:$pos";
} else {
echo "Keywords do not exist";
}
Using the writing method that is equal to ( !== false ) can accurately distinguish whether the function returns 0 or false , thereby avoiding logical errors.
For example, we want to detect whether the comments submitted by a user contain certain sensitive words and give a reminder: