In PHP, the stripos() function is a very practical tool when you need to find where a substring first appears in another string and search it hopefully. Its main advantage over strpos() is that strpos() ignores case differences when comparing. This article will explain step by step how to use the stripos() function and deepen your understanding through examples.
stripos() is a built-in function in PHP to find where a substring first appears in the main string. Its syntax is as follows:
int|false stripos(string $haystack, string $needle, int $offset = 0)
$haystack : The main string to search for.
$needle : The substring to be found.
$offset (optional): From which character position to start the search.
Return value :
If found, return the location where the substring first appears (starting at 0).
If not found, return false .
<?php
$text = "Welcome to M66.net!";
$position = stripos($text, "m66");
if ($position !== false) {
echo "The first time the substring appears is:$position";
} else {
echo "Substring not found";
}
?>
Output :
The first time the substring appears is:11
Note: Although "M66" is in the main string, we can successfully find the location with the lowercase "m66".
<?php
$text = "Visit m66.net and explore m66.net more!";
$position = stripos($text, "m66", 15);
if ($position !== false) {
echo "From15Start searching for characters,The substring appears at the location:$position";
} else {
echo "Substring not found";
}
?>
Output :
From15Start searching for characters,The substring appears at the location:28
Note: The first "m66" appears in position 6, but since we specified that we start searching from position 15, we found the second "m66" appears.
For case-sensitive comparisons, please use strpos() .
If $needle is an empty string, PHP will return 0 .
It is important to use === to strictly compare the return values, because both positions 0 and false are treated as false in non-strict comparisons.
Suppose we want to determine whether the URL the user access contains keywords, such as "login", to identify the login page:
<?php
$url = "https://m66.net/user/login";
if (stripos($url, "login") !== false) {
echo "This is a login page URL";
} else {
echo "Not a login page";
}
?>
Output :
This is a login page URL
stripos() is a very useful tool in PHP when processing strings, and is especially suitable for case-insensitive string search scenarios. By using it reasonably, your string processing logic can be made more concise and powerful. When processing data such as URLs and user input, it can effectively improve the robustness and fault tolerance of the code.