Est-il possible d'utiliser une expression régulière avec la fonction php array_key_exists()
?Fonction php array_key_exists et expressions régulières
Par exemple:
$exp = "my regex";
array_key_exists($exp, $array);
Merci!
Est-il possible d'utiliser une expression régulière avec la fonction php array_key_exists()
?Fonction php array_key_exists et expressions régulières
Par exemple:
$exp = "my regex";
array_key_exists($exp, $array);
Merci!
Vous pouvez extraire les clés du tableau à l'aide array_keys() puis utilisez preg_grep() sur ce tableau:
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);
}
Sortie:
$php a.php
int(1)
int(0)
Non, je ne crains pas. Vous pouvez itérer les clés du tableau et des correspondances avec les:
$keys = array_keys($array);
foreach ($keys as $key)
if (preg_match($exp, $key) == 1)
return $array[$key];
ou tout simplement si (preg_match (...)) dans le cas de plusieurs occurences de résultats. – zerkms
@zerkms: 'preg_match()' ne correspond qu'à la première occurrence du motif. Par conséquent, il ne peut retourner que "0" ou "1". S'il vous plaît voir http://php.net/preg_match –
au lieu de retourner, vous pouvez utiliser array_keys() – zerkms