Using array_key_exists with preg_match

I am trying to determine if a match or match exists in an array based on a template,

array example:

Array
(
    [author_id] => 1
    [channel_id] => 1
    [site_id] => 1
    [entry_id] => 6
    [url_title] => test_title_with_file2
    [title] => Test Title with file
    [field_id_1_directory] => 1
    [field_id_4_directory] => 1
    [submit] => Submit
    [entry_date] => 1278219110
)

I would like to determine whether the field_id_x_directory key , or the keys exist, and if they do, iterate over each of them and run a function that will use "x" as a variable.

Many thanks,

Iain.

+3
source share
3 answers
foreach (array_keys($arr) as $k) {
    if (preg_match('/^field_id_(\\d+)_directory$/', $k, $matches)) {
        //do sth with $arr[$k] and $matches[1]
    }
}
+11
source

A better alternative might be:

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
$keys = preg_grep( $pattern, array_keys( \$input ), \$flags );
$vals = array();
foreach ( $keys as $key )
{
    $vals[$key] = $input[$key];
}
return $vals;
}
+1
source
  $input = array (
  'hello'=>2,
  'hello stackoverflow'=>1,
  'hello world',
  'foo bar bas'=>4
);
$matches  = preg_grep ('/^hello$/i', array_keys($input));
 echo $input[$matches[0]];

will return 2

+1
source

Source: https://habr.com/ru/post/1753026/


All Articles