Find the index of an array that matches a regular expression

1

According to the PHP Manual, the preg_grep function returns the entries of a array that match the regular expression.

Example

$array = [
    'Banana',
    'Maçã',
    'Café',
    'Biscoito',
];

$array_com_B = preg_grep('/^B/i', $array);

Result:

['Banana', 'Biscoito']

But there is no function with this functionality to look up the indexes of a array that matches a regular expression.

I would like to return the keys of the array sampled below that match the regular expression /^(id|nome)$/i .

[
   'id' => 3,
   'idade' => 25,
   'nome'  => 'Wallace de Souza',
   'profissão' => 'Programador',

]
    
asked by anonymous 08.09.2015 / 17:43

1 answer

3

If you combine the functions array_keys , array_intersect_keys and array_flip , you'll get what you want:

$dados = [
    'id'        => 3,
    'idade'     => 25,
    'nome'      => 'Wallace de Souza',
    'profissão' => 'Programador',
];

$chaves = preg_grep('/^(id|nome)$/', array_keys($dados));
$dados = array_intersect_key($dados, array_flip($chaves));

Return:

Array
(
    [id] => 3
    [nome] => Wallace de Souza
)
    
08.09.2015 / 17:53