Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array_key_exists with preg_match

Tags:

arrays

regex

php

I'm trying to determine if a match, or matches exist within an array based on a pattern,

an example of the array:

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'd like to identify that the field_id_x_directory key, or keys exist, and if they do, loop over each one and run a function that would use the 'x' as a variable.

Many thanks,

Iain.

like image 758
iain Avatar asked Oct 31 '25 13:10

iain


2 Answers

foreach (array_keys($arr) as $k) {
    if (preg_match('/^field_id_(\\d+)_directory$/', $k, $matches)) {
        //do sth with $arr[$k] and $matches[1]
    }
}
like image 158
Artefacto Avatar answered Nov 03 '25 03:11

Artefacto


  $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

like image 25
Dragos Custura Avatar answered Nov 03 '25 04:11

Dragos Custura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!