$r = array_intersect_key($_POST, array_flip(preg_grep('/^empl_/', array_keys($_POST))));
they really need to add a PREG_GREP_KEYS
flag to preg_grep()
so we don't have to do all that mess...
作为一个函数:
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key(
$input,
array_flip(preg_grep(
$pattern,
array_keys($input),
$flags
))
);
}
编辑 - 从 php 5.6 开始array_filter
现在有一些新标志,可让您访问过滤器回调中的数组键。
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_filter($input, function($key) use ($pattern, $flags) {
return preg_match($pattern, $key, $flags);
}, ARRAY_FILTER_USE_KEY);
}
use
$filtered = preg_grep_keys('/^empl_/', $_POST);