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

PHP:如何从给定路径数组中获取当前路径的直接子目录?

获取当前路径的直接子目录数组

问题描述

给定路径数组,需要提取指定当前路径对应的直接子目录数组。示例如下:

$dirs = [
    '/chris',
    '/chris/usa',
    '/david',
    '/',
    '/chris/canada/2022',
    '/david/uk',
];
$current_path = "/chris";

// 期望结果:
$sub_dirs = ['/usa', '/canada'];

规则说明:

  • 当前路径可以是根目录/到任意层级子目录的路径
  • 若当前路径是最后一级子目录,结果为空数组

现有代码问题

你尝试的代码存在两个核心问题:

  1. 当当前路径为/时,返回的是去除斜杠后的路径(比如chris而非/chris)
  2. 当当前路径为/chris时,会包含更深层级的子目录(比如/canada/2022被截取为/canada/2022,不符合直接子目录要求)
$dirs = [
    '/chris',
    '/chris/usa',
    '/david',
    '/',
    '/chris/canada/2022',
    '/david/uk',
];

$sub_dirs = [];

$current_path = "/";

foreach($dirs as $dir){
    if(strstr($dir, $current_path)){
        $sub_dirs[] = str_replace($current_path, '', $dir);
    }
}

解决方案

以下是修正后的代码,通过路径标准化、精确前缀匹配和层级判断解决问题:

$dirs = [
    '/chris',
    '/chris/usa',
    '/david',
    '/',
    '/chris/canada/2022',
    '/david/uk',
];

$current_path = "/chris";
$sub_dirs = [];

// 标准化当前路径:非根目录去除结尾斜杠,根目录保持为"/"
$normalized_current = $current_path === '/' ? '/' : rtrim($current_path, '/');

foreach ($dirs as $dir) {
    // 跳过当前路径本身
    if ($dir === $normalized_current) {
        continue;
    }
    
    // 构建匹配前缀:根目录用"/",其他路径用"当前路径/"
    $prefix = $normalized_current === '/' ? $normalized_current : $normalized_current . '/';
    // 精确判断目录是否以目标前缀开头
    if (strpos($dir, $prefix) === 0) {
        // 截取当前路径之后的相对部分
        $relative = substr($dir, strlen($prefix));
        // 判断是否为直接子目录:相对路径中无斜杠
        if (strpos($relative, '/') === false) {
            $sub_dirs[] = '/' . $relative;
        }
    }
}

// 去重并排序(可选,根据需求调整)
$sub_dirs = array_unique($sub_dirs);
sort($sub_dirs);

print_r($sub_dirs);

关键逻辑说明

  1. 路径标准化:统一当前路径的格式,避免因结尾斜杠导致的匹配错误(比如/chris和/chris/视为同一路径)
  2. 精确前缀匹配:用strpos判断目录路径是否以目标前缀开头,确保匹配的是完整的父目录(避免/chris误匹配/chris2)
  3. 直接子目录判断:截取相对路径后,检查是否不含斜杠,确保只获取下一级目录,排除更深层级的路径
  4. 去重排序:保证结果数组无重复项,且输出有序

测试验证

  • 当$current_path = "/"时,结果为['/chris', '/david']
  • 当$current_path = "/chris"时,结果为['/canada', '/usa']
  • 当$current_path = "/david/uk"时,结果为空数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:50:25