溫馨提示×

php preg_match如何處理多維數組

PHP
小樊
81
2024-10-13 12:53:29
欄目: 編程語言

在PHP中,使用preg_match處理多維數組需要遍歷數組的每個元素并逐一檢查。以下是一個示例函數,用于在多維數組中搜索與正則表達式匹配的值:

function preg_match_in_array($pattern, $array) {
    $result = array();

    // 遍歷數組的每個元素
    foreach ($array as $key => $value) {
        // 如果當前元素是數組,則遞歸調用該函數
        if (is_array($value)) {
            $result = array_merge($result, preg_match_in_array($pattern, $value));
        } else {
            // 使用preg_match檢查當前元素是否與正則表達式匹配
            if (preg_match($pattern, $value)) {
                $result[] = array('key' => $key, 'value' => $value);
            }
        }
    }

    return $result;
}

使用此函數,您可以在多維數組中搜索與正則表達式匹配的值。例如:

$array = array(
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'address' => array(
        'street' => '123 Main St',
        'city' => 'New York',
        'zip' => '10001'
    )
);

$pattern = '/\d{5}/'; // 匹配5位數字的郵政編碼

$matches = preg_match_in_array($pattern, $array);

print_r($matches);

輸出結果:

Array
(
    [0] => Array
        (
            [key] => zip
            [value] => 10001
        )
)

這個示例中,preg_match_in_array函數遞歸地遍歷多維數組,并使用preg_match檢查每個元素是否與給定的正則表達式匹配。如果匹配成功,將鍵值對添加到結果數組中。

0