Current Location: Home> Latest Articles> Use array_filter() to filter out strings containing specific keywords

Use array_filter() to filter out strings containing specific keywords

M66 2025-06-04

In PHP, the array_filter() function can be used to filter elements in an array. It receives two parameters: the first is the array to be filtered, and the second is a callback function, which is used to determine which elements should be retained. This article will explain how to use array_filter() to filter out strings containing specific keywords in an array.

Basic usage

Suppose we have an array of multiple strings and we want to filter out strings that contain a specific keyword.

For example, suppose we have the following array:

 <?php
$urls = [
    "https://m66.net/products/item1",
    "https://m66.net/products/item2",
    "https://example.com/products/item3",
    "https://m66.net/about",
    "https://m66.net/contact"
];
?>

We want to filter out all strings containing m66.net through the array_filter() function.

Use array_filter() to filter strings

We can do this:

 <?php
$urls = [
    "https://m66.net/products/item1",
    "https://m66.net/products/item2",
    "https://example.com/products/item3",
    "https://m66.net/about",
    "https://m66.net/contact"
];

// Define filtering conditions:Only keep inclusion "m66.net" of URL
$filteredUrls = array_filter($urls, function($url) {
    return strpos($url, "m66.net") !== false;
});

// 输出过滤后of结果
print_r($filteredUrls);
?>

Code parsing

  1. array_filter() function : The array_filter() function will iterate through each element in the array $urls and pass each element to the callback function. The callback function checks whether the element contains the keyword m66.net .

  2. strpos() function : In the callback function, we use strpos() function to find out whether m66.net is included in the string. If strpos() returns false , it means that the string does not contain keywords, which we remove from the result; otherwise, the string contains keywords, retaining the element.

  3. Output : Finally, we use print_r() to output the filtered array.

result

After executing the above code, the output will be: