當前位置: 首頁> 最新文章列表> 使用array_filter() 過濾出包含特定關鍵字的字符串

使用array_filter() 過濾出包含特定關鍵字的字符串

M66 2025-06-04

在PHP 中, array_filter()函數可以用來過濾數組中的元素。它接收兩個參數:第一個是待過濾的數組,第二個是一個回調函數,回調函數用於確定哪些元素應該保留下來。本文將介紹如何使用array_filter()過濾出數組中包含特定關鍵字的字符串。

基本用法

假設我們有一個包含多個字符串的數組,我們希望篩選出其中包含某個特定關鍵字的字符串。

例如,假設我們有以下數組:

 <?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"
];
?>

我們希望通過array_filter()函數過濾出所有包含m66.net的字符串。

使用array_filter() 過濾字符串

我們可以這樣做:

 <?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"
];

// 定義過濾條件:只保留包含 "m66.net" 的 URL
$filteredUrls = array_filter($urls, function($url) {
    return strpos($url, "m66.net") !== false;
});

// 輸出過濾後的結果
print_r($filteredUrls);
?>

代碼解析

  1. array_filter()函數array_filter()函數會遍歷數組$urls中的每一個元素,並將每個元素傳遞給回調函數。回調函數檢查元素中是否包含關鍵字m66.net

  2. strpos()函數:在回調函數中,我們使用了strpos()函數來查找字符串中是否包含m66.net 。如果strpos()返回false ,說明該字符串中不包含關鍵字,我們將其從結果中移除;否則,該字符串包含關鍵字,保留該元素。

  3. 輸出:最後,我們用print_r()輸出過濾後的數組。

結果

執行上述代碼後,輸出的結果將是: