4

I have an large array like (simplified for convenience):

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
)

And wish to remove all key value pairs where the key starts with uploader_ (this can be a series) and also every occurrence of captcha_uid.

I've seen a useful example here: remove a key if value matches a pattern? but I'm terrible at regular expressions. How to optimally do this? Your views are much appreciated.

Community
  • 1
  • 1
chocolata
  • 3,258
  • 5
  • 31
  • 60

4 Answers4

12

You don't need regular expressions in such a simple case. Applying the accepted answer in the other question:

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

unset( $array[ 'captcha_uid' ] );
Community
  • 1
  • 1
JJJ
  • 32,902
  • 20
  • 89
  • 102
  • Thank you. Although the other answers will also work, I accepted this one because you explicitly did not use regular expressions. – chocolata Jul 12 '12 at 10:28
3

try this one :

$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);
Somy A
  • 1,682
  • 15
  • 18
1

You can use a foreach with the PHP function preg_match. Something like that.

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

As of PHP 5.6.0 (ARRAY_FILTER_USE_KEY) you can also do this way:

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

Ref: array_filter

DrLightman
  • 575
  • 6
  • 13