相当于 glob() ,它可以使用数组而不是文件系统

Gaj*_*jus 2 php regex algorithm amazon-s3

原始标题是仅从特定对象路径(S3,Google Storage)列出目录/文件的算法

https://gist.github.com/9a353e1589ff3ce84c02

任何人都可以建议一种算法来仅在特定对象路径中列出目录/文件吗?例如ahostel.lt/img/应该只列出 directoies languages and psd, and files background.png, [..]。我的算法很长,并且使用了三个 foreach 循环,这对性能不利,但也许任何人都知道如何使用正则表达式或其他替代方法来实现它。

我的系统在 PHP 上运行,但只要可以将其转换为 PHP,一般对数就可以了。

换句话说,我正在寻找一种像 glob() 这样的算法,它可以与数组而不是文件系统一起使用。

简化目录列表:https : //gist.github.com/d0c3fa12d4b894938ba5

sal*_*the 5

看起来你有一个简单的数组,所以这里有一个替代方法,它使用键上的正则表达式过滤数组。

// Matches only immediate files of ahostel.lt/img/
$pattern = '#^ahostel\.lt/img/[^/]+\.[^/]+$#D';
$keys    = preg_grep($pattern, array_keys($array));
$items   = array_intersect_key($array, array_flip($keys));
Run Code Online (Sandbox Code Playgroud)

另一种方法,由于迭代器很棒,无需编写定制的迭代器,就可以使用 aRegexIterator来完成过滤键的工作。然后,您只需遍历过滤后的迭代器,或者使用它iterator_to_array()来获取仅包含过滤值的数组。

$items = new RegexIterator(
    new ArrayIterator($array),
    '#^ahostel\.lt/img/[^/]+\.[^/]+$#D',
    RegexIterator::MATCH,
    RegexIterator::USE_KEY
);
Run Code Online (Sandbox Code Playgroud)

有无数种不同的方式可以使用或创建迭代器过滤,甚至可以fnmatch()在 a 的accept()方法中FilterIterator使用诸如 with 之类的通配符模式glob()

class GlobKeyFilterIterator extends FilterIterator
{
    protected $pattern;
    public function __construct(Iterator $it, $pattern)
    {
        $this->pattern = $pattern;
        parent::__construct($it);
    }
    public function accept()
    {
        return fnmatch($this->pattern, $this->key(), FNM_PATHNAME);
    }
}

$items = new GlobKeyFilterIterator(
    new ArrayIterator($array),
    'ahostel.lt/img/*.*'
);
Run Code Online (Sandbox Code Playgroud)