It is a common requirement to process URLs and their parameters in PHP, especially in scenarios such as jump judgment, record source or security verification. stripos() is a very practical function that can be used to determine whether a string contains another string, and yes.
This article will introduce how to use stripos() to check whether a URL contains specified parameters, such as ref=abc , utm_source , etc.
stripos() is a built-in function of PHP, and its usage is as follows:
int|false stripos(string $haystack, string $needle, int $offset = 0)
It returns the location where the needle first appears in haystack and false if not found. Unlike strpos() , strpos() is case-insensitive.
Suppose we have a URL:
$url = "https://m66.net/shop/product.php?id=123&ref=abc&utm_source=google";
We want to check whether this URL contains the parameter ref=abc .
<?php
$url = "https://m66.net/shop/product.php?id=123&ref=abc&utm_source=google";
// Parameters to be found
$param = "ref=abc";
// use stripos Do a search
if (stripos($url, $param) !== false) {
echo "URL Includes parameters '{$param}'。";
} else {
echo "URL No parameters are included '{$param}'。";
}
Output result:
URL Includes parameters 'ref=abc'。
stripos() returns the matching position , not the boolean value, so you need to use !== false to determine whether the match is successful.
stripos() is case-insensitive, if you want case-sensitive checks, please use strpos() .
If you want to detect multiple parameters, it is recommended to use them in combination with loops, or parse the parameters into an array and then process them.
<?php
$url = "https://m66.net/shop/product.php?id=123&ref=abc&utm_source=google";
$params = ["ref=abc", "utm_source=google", "campaign=summer"];
foreach ($params as $param) {
if (stripos($url, $param) !== false) {
echo "URL Include parameters:{$param}\n";
} else {
echo "URL 不Include parameters:{$param}\n";
}
}
Using stripos() is a simple and quick way to check if there are certain keywords or parameters in the URL. It is a perfect tool when you don't care about case, or just want to do a simple include check.
If you need more rigorous URL parsing (such as extracting parameter values, constructing query strings, etc.), you can consider using functions such as parse_url() and parse_str() .
Hope this article helps you! If you have any further questions, please continue to communicate!