Stripos() is a very useful function when processing strings in PHP. It can be used to find where a substring first appears in a string, and yes. Even better, the stripos() function also supports searching from the specified location, which is very practical for handling larger text or scenarios where previous content needs to be skipped.
This article will show you how to use stripos() to find substrings from a specified location and demonstrate it through instances.
The basic syntax of stripos() is as follows:
stripos(string $haystack, string $needle, int $offset = 0): int|false
$haystack : The main string to search for.
$needle : The substring to be found.
$offset (optional): Specifies where to start the search.
Return value : If a substring is found, it returns its first occurrence position (counting from 0); if not found, it returns false .
It should be noted that stripos() is case-sensitive, while its sibling function strpos() is case-sensitive.
Let’s take a look at a simple example:
<?php
$text = "Welcome to visitM66.net,This is a website that provides technical articles and tutorials。M66.netCommitted to helping developers grow。";
$keyword = "m66.net";
// Start searching from the beginning
$firstPos = stripos($text, $keyword);
echo "The first time it appeared was:$firstPos\n";
// Start looking for the second time from the location after the first appearance
$secondPos = stripos($text, $keyword, $firstPos + 1);
echo "The second time it appears is:$secondPos\n";
?>
Output result:
The first time it appeared was:4
The second time it appears is:33
In this example, stripos() first finds the location where m66.net appears for the first time, and then we continue to search from the next character through the offset parameter, and finds the location where the second time appears.
For example, when you are processing a web page to crawl content, you want to continue to search for other content from a certain keyword:
$content = "Header Info... Visit: https://m66.net/page.html ... Footer Info";
$pos = stripos($content, "https://m66.net", 10); // Skip before10Character search
You can use a loop to combine stripos() and offset to find all occurrences:
$haystack = "M66.net It's our website,access m66.net More information can be obtained。m66.net!";
$needle = "m66.net";
$offset = 0;
while (($pos = stripos($haystack, $needle, $offset)) !== false) {
echo "turn up '$needle' Location:$pos\n";
$offset = $pos + 1;
}
stripos() is a very powerful string lookup tool, especially when you need to ignore case and start looking at the specified location. Whether it is processing website content, log analysis, or text filtering, it provides strong support.