2010-03-18 4 views

Répondre

30

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) 
+1

au lieu de retourner, vous pouvez utiliser array_keys() – zerkms

3

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]; 
+0

ou tout simplement si (preg_match (...)) dans le cas de plusieurs occurences de résultats. – zerkms

+1

@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 –