Reputation: 2207
I have and array with paths to files, but I need to filter out certain folders.
This is just an example but I want to remove files that are in this case in folders like 'thumbs', 'database' & 'test'.
I could not find an array filter for this.
[
[0] => uploads/projects/pathtofile.jpg,
[1] => uploads/projects/thumbs/pathtofile.jpg,
[3] => uploads/database/projects/pathtofile.jpg,
[4] => uploads/projects/thumbs/database/pathtofile.jpg,
[5] => uploads/thumbs/projects/test/pathtofile.jpg
]
Upvotes: 0
Views: 72
Reputation: 814
What about using array_filter callable?
<?php
$a = array(
0 => 'uploads/projects/pathtofile.jpg',
1 => 'uploads/projects/thumbs/pathtofile.jpg',
3 => 'uploads/database/projects/pathtofile.jpg',
4 => 'uploads/projects/thumbs/database/pathtofile.jpg',
5 => 'uploads/thumbs/projects/test/pathtofile.jpg',
6 => 'uploads/thumb/projects/pathtofile.jpg'
);
$b = array_values(array_filter($a, function ($item) {
return !preg_match('/(\/thumbs\/|\/database\/|\/test\/)/', $item);
}));
echo '<pre>' . print_r($b, 1) . '</pre>';
Output:
Array
(
[0] => uploads/projects/pathtofile.jpg
[1] => uploads/thumb/projects/pathtofile.jpg
)
Upvotes: 0
Reputation: 1791
If your file path starts with /
then this would work fine:
$blacklist = ['/thumb/', '/image/'];
$files = ['/dir/thumb/image.jpg', '/dir/image/thumb.jpg', '/dir/subdir/file.php'];
$filtered_files = array_filter($files, function($value) use($blacklist){
foreach($blacklist as $blk){
if(strpos($value, $blk) !== false){
return false;
}
}
return true;
});
print_r($filtered_files);
Output :
Array
(
[2] => /dir/subdir/file.php
)
Upvotes: 0
Reputation: 3401
I'd go with array_filter()
and preg_match()
:
$filtered = array_filter($a, function($i) {
return preg_match('/(thumbs|database|test)/', $i) !== 1;
});
Upvotes: 0
Reputation: 72269
You can use array_interset()
foreach($array as $key=> $ar){
if(count(array_intersect(explode('/',$ar),['thumbs', 'database','test']))>0){
unset($array[$key]);
}
}
Output:- https://eval.in/939916
Upvotes: 2