In PHP development, we often need to filter elements in arrays, especially when we want to find string elements that contain certain keywords. At this time, the combination of stripos and array_filter is a very practical solution.
This article will take you step by step to understand how to use stripos with array_filter to implement this function.
stripos() is a string function in PHP that finds where a string first appears in another string (case insensitive). Returns the location if found (starting from 0), and returns false if not found.
The syntax is as follows:
stripos(string $haystack, string $needle): int|false
For example:
stripos("Hello World", "world"); // return 6
array_filter() is a function in PHP used to filter arrays by callback functions. It will iterate over each element in the array and filter out elements that do not match the return value of the callback function.
The syntax is as follows:
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
Let's take a look at a practical example: we have an array containing multiple URLs, and we want to filter out all elements containing a certain keyword (such as "login".
<?php
$urls = [
"https://m66.net/home",
"https://m66.net/user/login",
"https://m66.net/about",
"https://m66.net/admin/login",
"https://m66.net/contact"
];
$keyword = "login";
$filtered = array_filter($urls, function($url) use ($keyword) {
return stripos($url, $keyword) !== false;
});
print_r($filtered);
Array
(
[1] => https://m66.net/user/login
[3] => https://m66.net/admin/login
)
As you can see, only the URLs containing "login" are preserved.
If you want to support multiple keywords, you can modify the callback function slightly:
<?php
$keywords = ["login", "admin"];
$filtered = array_filter($urls, function($url) use ($keywords) {
foreach ($keywords as $word) {
if (stripos($url, $word) !== false) {
return true;
}
}
return false;
});
print_r($filtered);
This will return a URL containing either keyword, flexible and powerful.
Using stripos with array_filter is a simple and efficient way to handle keyword matching in string arrays. It not only has concise code and clear logic, but also is suitable for a variety of practical scenarios, such as log analysis, URL routing matching, content filtering, etc.
You can further encapsulate this logic into a function according to your needs to improve reusability and maintainability.
If you are interested in this type of PHP practical skills, please follow more programming tips!