Domanda

I'm trying to use preg_grep to return an array of only keys matched with the existence of 3 specific letters i.e.

array as follows:

$testArray = array(
'XXL' => array(),
'XL' => array(),
'L' => array(),
'M' => array(),
'S' => array(),
'XS' => array()
);

I want to run something like (if I can get it to work :) )

$res = preg_grep('[^XLS]', $testArray);

and get a returned array without the 'M' key i.e.

$res = array(
'XXL' => array(),
'XL' => array(),
'L' => array(),
'S' => array(),
'XS' => array()
);

I've tried multiple regex's but I get either all the keys or none, can anyone help please??

Many thanks, Kieron

È stato utile?

Soluzione

preg_grep() will not work with multi-dimensional arrays. You'll have to fetch the keys separately using array_keys() and apply preg_grep() on that. Now use array_intersect_key() in conjunction with array_flip() to create the result array:

$keys = preg_grep('/[XLS]/', array_keys($testArray));
$result = array_intersect_key($testArray, array_flip($keys));

Output:

Array
(
    [XXL] => Array
        (
        )

    [XL] => Array
        (
        )

    [L] => Array
        (
        )

    [S] => Array
        (
        )

    [XS] => Array
        (
        )

)

Demo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top