从数组中过滤某些文件夹

时间:2018-01-22 11:42:32

标签: php

我有和文件路径的数组,但我需要过滤掉某些文件夹。

这只是一个示例,但我想删除这种情况下的文件,例如' thumbs','数据库' &安培; '测试'

我找不到这个数组过滤器。

[
   [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

]

4 个答案:

答案 0 :(得分:2)

您可以使用array_interset()

foreach($array as $key=> $ar){
   if(count(array_intersect(explode('/',$ar),['thumbs', 'database','test']))>0){
    unset($array[$key]);
  }
}

输出: - https://eval.in/939916

答案 1 :(得分:0)

如何使用array_filter callable?

sub-menu and sub-sub-menu

输出:

<?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>';

答案 2 :(得分:0)

我选择array_filter()preg_match()

$filtered = array_filter($a, function($i) {
    return preg_match('/(thumbs|database|test)/', $i) !== 1;
});

答案 3 :(得分:0)

如果您的文件路径以/开头,那么这样可以正常工作:

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

输出:

Array
(
[2] => /dir/subdir/file.php
)