In PHP programming, processing strings is one of the most common tasks in daily development. And when you need to find the location of a substring in a string, and you don't want to be case sensitive, the stripos() function will be a very practical tool.
stripos() is a function in PHP that finds the first occurrence of a substring in the target string. The main difference with strpos() is that strpos() is case-insensitive , which makes it very convenient when handling user input, URL parameter matching, or insensitive searches.
The function prototype is as follows:
int|false stripos(string $haystack, string $needle, int $offset = 0)
$haystack : The target string to search for.
$needle : The substring to be found.
$offset (optional): Starts the search from the first character of the target string.
Return value: Returns the position where the substring first appears (starting from 0) when successful, and returns false when failure.
<?php
$text = "Welcome to M66.NET, the best place to learn PHP!";
$position = stripos($text, "m66");
if ($position !== false) {
echo "Substring 'm66' The first appearance is:$position";
} else {
echo "未找到Substring 'm66'";
}
?>
The output result is:
Substring 'm66' The first appearance is:11
Even though the original string is capitalized M66.NET , stripos() still successfully found m66 because it is case-insensitive.
<?php
$url = "https://m66.net/blog/php-guide";
$position = stripos($url, "PHP", 10);
if ($position !== false) {
echo "In offset 10 back,'PHP' The location where it appears is:$position";
} else {
echo "Offset 10 back未找到 'PHP'";
}
?>
In this example, we start looking for "PHP" from the 10th character, which is suitable for scenarios such as skipping the URL protocol part.
stripos() returns the position index, starting from 0; if the returned false , be careful to use congruent === to judge to avoid misjudging the position 0.
If you want to do a case-sensitive search, use strpos() .
URL check : For example, determine whether the link submitted by the user contains a certain keyword.
Search suggestions : Users perform fuzzy matches when entering content in the search box.
Text Analysis : Find whether the article contains certain keywords, regardless of upper and lower case.