如果键包含(匹配)一个或多个子字符串,如何从PHP数组中删除键值对


How to remove key value pairs from a PHP array if the key contains (matches) one or more substrings

我有一个大数组,类似(为了方便起见简化了):

Array
(
    [last_name] => Ricardo 
    [first_name] => Montalban
    [sex] => Yes please
    [uploader_0_tmpname] => p171t8kao6qhj1132l14upe14rh1.jpg
    [uploader_0_name] => IMAG0114-1.jpg
    [uploader_0_status] => done
    [uploader_count] => 1
    [captcha_uid] => 155
)

并希望删除所有密钥以uploader_开头的键值对(这可以是一个序列),以及captcha_uid的每次出现。

我在这里看到了一个有用的例子:如果值与模式匹配,是否删除键?但我不擅长正则表达式。如何以最佳方式做到这一点?非常感谢你的意见。

在这种简单的情况下,您不需要正则表达式。在另一个问题中应用已接受的答案:

foreach( $array as $key => $value ) {
    if( strpos( $key, 'uploader_' ) === 0 ) {
        unset( $array[ $key ] );
    }
}
unset( $array[ 'captcha_uid' ] );

试试这个:

$data = array(
    'last_name' => 'Ricardo',
    'first_name' => 'Montalban',
    'sex' => 'Yes please',
    'uploader_0_tmpname' => 'p171t8kao6qhj1132l14upe14rh1.jpg',
    'uploader_0_name' => 'IMAG0114-1.jpg',
    'uploader_0_status' => 'done',
    'uploader_count' => '1',
    'captcha_uid' => '155',
);
foreach($data as $key => $value) {
    if(preg_match('/uploader_(.*)/s', $key)) {
        unset($data[$key]);
    }
}
unset($data['captcha_uid']);
print_r($data);

您可以将foreach与PHP函数preg_match一起使用。类似的东西。

foreach($array as $key => $value) {
  if(!preg_match("#^uploader_#", $key)) {
    unset($array[$key]);  
  }
}

从PHP 5.6.0(ARRAY_FILTER_USE_KEY)开始,您也可以这样做:

$myarray = array_filter( $myarray, function ( $key ) {
    return 0 !== strpos( $key, 'uploader_' ) && 'captcha_uid' != $key;
} , ARRAY_FILTER_USE_KEY );

参考:array_filter