使用通配符搜索数组键


Search array keys with wildcard

假设我有以下数组:

$arr = array(
   "number2"=>"valid",
   "number13"=>"valid"
);

,我需要找到是否存在一个键与number*

对于$arr,这是正确的。对于以下数组:

$arr2 = array(
   "key"=>"foo",
   "key2"=>"foo2"
);

这将返回false

这个假设数字后面需要一个实际的数字(编辑:或者什么都不写),根据需要调整正则表达式。例如,任何以'number'开头的内容,都可以使用/^number/

if(count(preg_grep('/^number['d]*/', array_keys($arr))) > 0)
{
   return true;
}
else
{
   return false;
}

使用正则表达式

foreach ($arr as $key => $value) {
  // NOTE: check for the right format of the regular expression 
  if (preg_match("/^number([0-9]*)$", $key)) {
    echo "A match was found.";
  } else {
    echo "A match was not found.";
  }
}

下面是一个简单的函数,它会做你想做的:

function preg_grep_key($pattern, $input) {
    return preg_grep($pattern, array_keys($input));
}
// ----- Usage -----
$arr = array(
   "number2"=>"valid",
   "number13"=>"valid"
);

if (count(preg_grep_key('/^number/', $arr)) === 0) {
    // Nope
} else {
    // Yep
}

EPB和Dan Horrigan做得对,但从代码整洁的角度来看,让我把它们留在这里:

如果你只想返回真或假,你不需要If语句;仅返回preg_grep()empty()检查结果:

return !empty(preg_grep('/^number['d]*/', array_keys($arr));

如果你需要运行一个' If '检查,count()!empty()已经返回真/假,你不需要再次检查它们的值:

if ( count( preg_grep('/^number['d]*/', array_keys( $arr )) ) ) {
   // Action when it is true
} else {
   // Action when it is false
}

我个人更喜欢empty()而不是计算结果数组元素,因为类型一致性:

if ( !empty( preg_grep('/^number['d]*/', array_keys( $arr )) ) ) {
   // Action when it is true
} else {
   // Action when it is false
}

关于true/false的更多信息,即当语句的计算结果为true/false时:https://www.php.net/manual/en/language.types.boolean.php