A shorter way to run a match on the array's keys rather than the values:
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
preg_grep — Return array entries that match the pattern
Returns the array consisting of the elements of the
array
array that match the given
pattern
.
pattern
The pattern to search for, as a string.
array
The input array.
flags
If set to PREG_GREP_INVERT
, this function returns
the elements of the input array that do not match
the given pattern
.
Returns an array indexed using the keys from the
array
array, or false
on failure.
If the regex pattern passed does not compile to a valid regex, an E_WARNING
is emitted.
Example #1 preg_grep() example
<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>
A shorter way to run a match on the array's keys rather than the values:
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
Run a match on the array's keys rather than the values:
<?php
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;
}
?>
This may be obvious to most experienced developers,but just in case its not,when using preg_grep to check for whitelisted items ,one must be very careful to explicitly define the regex boundaries or it will fail
<?php
$whitelist = ["home","dashboard","profile","group"];
$possibleUserInputs = ["homd","hom","ashboard","settings","group"];
foreach($possibleUserInputs as $input)
{
if(preg_grep("/$input/i",$whitelist)
{
echo $input." whitelisted";
}else{
echo $input." flawed";
}
}
?>
This results in:
homd flawed
hom whitelisted
ashboard whitelisted
settings flawed
group whitelisted
I think this is because if boundaries are not explicitly defined,preg_grep looks for any instance of the substring in the whole array and returns true if found.This is not what we want,so boundaries must be defined.
<?php
foreach($possibleUserInputs as $input)
{
if(preg_grep("/^$input$/i",$whitelist)
{
echo $input." whitelisted";
}else{
echo $input." flawed";
}
}
?>
this results in:
homd flawed
hom flawed
ashboard flawed
settings flawed
group whitelisted
in_array() will also give the latter results but will require few tweaks if say,the search is to be case insensitive,which is always the case 70% of the time
An even shorter way to run a match on the array's keys rather than the values:
<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_flip( preg_grep($pattern, array_flip($input), $flags ) );
}
?>