Let\'s say my $_POST
variable looks like:
65
[action] => editpost
[originalaction] => editpo
$empl_post = array();
foreach ($_POST as $k => $v) {
if (strpos($k, 'empl_') !== 0) continue;
$empl_post[substr($k, 5)] = $v
}
print_r($empl_post);
Another method:
$formVars = $_POST;
foreach ($formVars as $key=>$value) {
if (strpos($key, 'empl_')===false)
unset($formVars[$key]);
}
function GetPrefixedItemsFromArray($array, $prefix)
{
$keys = array_keys($array);
$result = array();
foreach ($keys as $key)
{
if (strpos($key, $prefix) === 0)
{
$result[$key] = $array[$key];
}
}
return $result;
}
Then simply call with $myArray = GetPrefixedItemsFromArray($_POST, "empl_");
.
Here's a cool ultra-php-neat way to use php array_walk to specify a generic prefix to remove:
$foo = array('k_foo' =>"bar",
'k_bar' =>"b0r",
'y_foo' =>"b5r",
'y_not' =>"b7r",
'k_not' =>"b1r");
$subsetArray = $foo;
$key_prefix = "k_";
array_walk($foo, 'removeUnwanted', array(&$subsetArray, $key_prefix));
var_dump ($subsetArray);
function removeUnwanted($value, $key, $array){
$prefix = $array[1];
$testArray = &$array[0];
if(strpos($key,$prefix) ===0){
unset($testArray[$key]);
}
}
Now you can just call array walk, with a copy of the array of values, and the prefix string.
If you want something like this
$keyPattern = '/^empl_*/';
$matching_array = getArrayElementsWithMatchingKeyPattern($_POST,$keyPattern);
Then I dont think there is an inbuilt way to that. Best way would be a foreach loop with a regex match.
function getArrayElementsWithMatchingKeyPattern($array,$keyPattern){
$matching_array = array();
foreach ($keyPattern as $k => $v) {
if (preg_match($array[$k],$keyPattern) > 0)
$matching_array[$k] = $v;
}
return ($matching_array);
}
$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...
As a function:
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key(
$input,
array_flip(preg_grep(
$pattern,
array_keys($input),
$flags
))
);
}
Edit - since php 5.6 array_filter
now has some new flags that let you access the array key in the filter callback.
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);