2010-03-18 6 views

Antwort

30

Sie können die Array-Schlüssel extrahieren array_keys() und anschließend preg_grep() verwenden, um auf diesem 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); 
} 

Ausgang:

$php a.php 
int(1) 
int(0) 
+1

anstelle von spiegeln können Sie array_keys() verwenden – zerkms

3

Nein, ich fürchte nicht. Sie können die Schlüssel für das Array durchlaufen und führen Matches auf denen:

$keys = array_keys($array); 
foreach ($keys as $key) 
    if (preg_match($exp, $key) == 1) 
    return $array[$key]; 
+0

oder if (preg_match (...)) im Falle mehrerer Ergebnis occurencies. – zerkms

+1

@zerkms: 'preg_match()' entspricht nur dem ersten Auftreten des Musters. Daher kann nur "0" oder "1" zurückgegeben werden. Bitte sehen Sie http://php.net/preg_match –