Find the index of an array that matches a regular expression

Asked

Viewed 118 times

1

According to the PHP Handbook, the function preg_grep returns the entries of a array which combine with regular expression.

Example

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

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

Upshot:

['Banana', 'Biscoito']

But there is no function with this feature to search the contents of a array to match a regular expression.

I’d like to return the keys to the array exemplified below that match the regular expression /^(id|nome)$/i.

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

]

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
)
  • 1

    +1. I see much this call from array_intersect_key with array_flip in the source codes of Laravel 4.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.