Is it possible to use a regular expression with the php function array_key_exists()
?
For example:
$exp = "my regex"; array_key_exists($exp, $array);
Thank you!
Definition and Usage. The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys.
preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_replace() in PHP – this function is used to perform a pattern match on a string and then replace the match with the specified text.
In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers. $exp = "/w3schools/i"; In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.
You can extract the array keys using array_keys() and then use preg_grep() on that array:
function preg_array_key_exists($pattern, $array) { $keys = array_keys($array); return (int) preg_grep($pattern,$keys); }
.
$arr = array("abc"=>12,"dec"=>34,"fgh"=>56); var_dump(preg_array_key_exists('/c$/',$arr)); // check if a key ends in 'c'. var_dump(preg_array_key_exists('/x$/',$arr)); // check if a key ends in 'x'. function preg_array_key_exists($pattern, $array) { // extract the keys. $keys = array_keys($array); // convert the preg_grep() returned array to int..and return. // the ret value of preg_grep() will be an array of values // that match the pattern. return (int) preg_grep($pattern,$keys); }
Output:
$php a.php int(1) int(0)
No, I'm afraid not. You can iterate the array keys and perform matches on those:
$keys = array_keys($array); foreach ($keys as $key) if (preg_match($exp, $key) == 1) return $array[$key];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With