Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function array_key_exists and regular expressions

Tags:

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!

like image 752
Bacon Avatar asked Mar 18 '10 15:03

Bacon


People also ask

What is array_key_exists?

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.

What is PHP function Array_keys () used for?

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.

What is the purpose of Preg_match () regular expression in PHP?

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.

Does PHP support regex?

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.


2 Answers

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) 
like image 53
codaddict Avatar answered Oct 11 '22 00:10

codaddict


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]; 
like image 43
St. John Johnson Avatar answered Oct 11 '22 02:10

St. John Johnson