You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中能否使用glob模式匹配zip压缩包内的文件?

问题根因

PHP原生glob()函数仅支持本地物理文件系统路径,不识别zip://这类流包装器路径;同时zip://流本身未实现目录遍历接口,因此你测试的scandir()调用会返回空数组。

可行实现方案

可以用PHP内置的ZipArchive扩展实现zip包内文件的匹配筛选,代码示例如下:

基础实现(筛选指定子目录下指定后缀的文件)

<?php
$zipPath = 'path/to/archive.zip';
// 要匹配的子目录前缀
$targetDir = 'subdir/';
// 要匹配的文件后缀
$targetExt = 'ext';

$zip = new ZipArchive();
$matched = [];

if ($zip->open($zipPath) === true) {
    // 遍历压缩包内所有条目
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $fileInfo = $zip->statIndex($i);
        $filePath = $fileInfo['name'];
        
        // 过滤目标目录下的文件,排除目录条目(目录名以/结尾)
        if (str_starts_with($filePath, $targetDir) && !str_ends_with($filePath, '/')) {
            // 匹配指定后缀
            if (pathinfo($filePath, PATHINFO_EXTENSION) === $targetExt) {
                $matched[] = $filePath;
                // 如需读取文件内容可直接调用:$content = $zip->getFromIndex($i);
            }
        }
    }
    $zip->close();
}

var_dump($matched);

低版本PHP兼容说明

如果使用的是PHP8.0以下版本,没有内置str_starts_with、str_ends_with函数,可替换为以下写法:

  • 前缀匹配:substr($filePath, 0, strlen($targetDir)) === $targetDir
  • 后缀匹配:substr($filePath, -1) === '/'

支持完整glob模式匹配

如果需要实现更复杂的glob规则匹配,可以直接用PHP内置的fnmatch函数判断:

// 替换上述的条件判断即可支持glob规则
if (fnmatch('subdir/*.ext', $filePath) && !str_ends_with($filePath, '/')) {
    $matched[] = $filePath;
}

内容的提问来源于stack exchange,提问作者tim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:54:04