Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active December 7, 2019 00:04
Show Gist options
  • Select an option

  • Save stemar/9a06b2de786cef674eae9ab1330b1c03 to your computer and use it in GitHub Desktop.

Select an option

Save stemar/9a06b2de786cef674eae9ab1330b1c03 to your computer and use it in GitHub Desktop.
Filter in or out keys with a regex pattern
<?php
/**
* Get array entries that match pattern in their keys.
*
* @link https://www.php.net/manual/en/function.preg-grep.php
* @param string $pattern
* @param array $assoc
* @param int $flags 0 or PREG_GREP_INVERT
* @return array
*/
function preg_grep_keys($pattern, array $assoc, $flags=0) {
$grep = preg_grep((string)$pattern, array_keys($assoc), (int)$flags);
return array_intersect_key($assoc, array_flip($grep));
}
<?php
$date_constants = preg_grep_keys('/^DATE_/', get_defined_constants());
print_r($date_constants);
/*
Array
(
[DATE_ATOM] => Y-m-d\TH:i:sP
[DATE_COOKIE] => l, d-M-Y H:i:s T
[DATE_ISO8601] => Y-m-d\TH:i:sO
[DATE_RFC822] => D, d M y H:i:s O
[DATE_RFC850] => l, d-M-y H:i:s T
[DATE_RFC1036] => D, d M y H:i:s O
[DATE_RFC1123] => D, d M Y H:i:s O
[DATE_RFC2822] => D, d M Y H:i:s O
[DATE_RFC3339] => Y-m-d\TH:i:sP
[DATE_RSS] => D, d M Y H:i:s O
[DATE_W3C] => Y-m-d\TH:i:sP
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment