PHP数组仅获取其键与特定模式匹配的元素/值

时间:2017-09-02 13:05:25

标签: php arrays regex pattern-matching array-key

我有一个多维&嵌套数组如下:

Array
(
    [_edit_lock] => Array
        (
            [0] => 1504299434:6
        )

    [_edit_last] => Array
        (
            [0] => 6
        )
    [additional_photos_0_gallery_image_1] => Array
        (
            [0] => 77556
        )
    [additional_photos_0_gallery_image_2] => Array
        (
            [0] => 77567
        )
    [additional_photos_0_gallery_image_3] => Array
        (
            [0] => 73768
        )
    ....
)

现在我只需要获取给定数组的那些元素(在不改变当前数组的单独数组中),其键与下面的特定模式匹配:

additional_photos_[any_number]_gallery_image_[any_number]

如何使用其中一个数组函数并避免foreach循环?

1 个答案:

答案 0 :(得分:1)

只需使用array_filter和preg_match。

return array_filter($data, function($key) {
    return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
}, ARRAY_FILTER_USE_KEY);