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

PHP递归搜索目录文件:rsearch函数调用与结果获取示例

PHP递归搜索文件实现及调用示例

递归搜索函数实现

先定义递归遍历目录的rsearch函数,它会遍历指定目录及所有子目录,返回符合文件名匹配条件的文件路径数组:

function rsearch($dir, $pattern) {
    $files = [];
    foreach(scandir($dir) as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($path)) {
            $files = array_merge($files, rsearch($path, $pattern));
        } else {
            // 匹配文件名包含指定字符串(区分大小写)
            if (strpos($item, $pattern) !== false) {
                $files[] = $path;
            }
        }
    }
    return $files;
}

调用示例:搜索含“apple”的文件

以下是完整的调用逻辑,包括获取结果、生成适配内部网站的下载链接:

// 替换为你的培训文档根目录路径
$rootDir = './training_docs';
// 要搜索的关键词
$searchKeyword = 'apple';

// 执行搜索
$matchedFiles = rsearch($rootDir, $searchKeyword);

// 输出搜索结果
if (!empty($matchedFiles)) {
    echo '<h3>找到包含"' . htmlspecialchars($searchKeyword) . '"的文件:</h3>';
    echo '<ul>';
    foreach ($matchedFiles as $file) {
        // 转换为网站可访问的URL路径
        $relativePath = str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', realpath($file));
        $fileUrl = str_replace('\\', '/', $relativePath);
        // 生成下载链接
        echo '<li>
                <a href="' . htmlspecialchars($fileUrl) . '">' . htmlspecialchars(basename($file)) . '</a>
                <span style="margin-left:10px;color:#666;">路径:' . htmlspecialchars($file) . '</span>
              </li>';
    }
    echo '</ul>';
} else {
    echo '<p>未找到包含"' . htmlspecialchars($searchKeyword) . '"的文件</p>';
}

额外说明

  • 若需要不区分大小写搜索,将函数中的strpos替换为stripos即可。
  • 确保PHP进程拥有目标目录及子目录的读取权限,否则无法正常遍历。
  • 使用htmlspecialchars处理输出内容,避免XSS安全问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:15:58