簡體   English   中英

如果密鑰包含(匹配)一個或多個子字符串,如何從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);

你可以使用帶有PHP函數preg_matchforeach 這樣的事情。

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 );

Ref: array_filter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM