【问题标题】:How to get last & second last folder name from path using php?如何使用php从路径中获取最后一个和倒数第二个文件夹名称?
【发布时间】:2020-08-15 16:15:10
【问题描述】:

路径:

Home/Gallery/Images/Mountains

此路径中的最后一个文件夹名称是 Mountains,倒数第二个文件夹名称是 Images。


我想显示这个输出:

Last folder: Mountains
Second last folder: Images

是否可以使用 substr 或任何其他方式。这里有谁能给我答案吗?谢谢

【问题讨论】:

    标签: php path substr


    【解决方案1】:

    这是一个使用basename 和dirname 的简单选项:

    $path = 'Home/Gallery/Images/Mountains';
    $lastFolder = basename($path);
    $secondToLastFolder = basename(dirname($path));
    

    Demo

    【讨论】:

      【解决方案2】:

      只需 2 个小步骤:​​

      1. 用“/”分割
      2. 取出数组的最后 2 项
      $path = "Home/Gallery/Images/Mountains";
      $parts = explode("/", $path);
      $folders = array_slice($parts, -2);
      

      然后,您将在 $folders 数组中拥有两个可用的文件夹

      我强烈建议您在此处阅读有关 array_slice 的更多信息:https://www.php.net/manual/en/function.array-slice.php

      【讨论】:

      • 显示此错误:注意:Array to string conversion in C:\Xampp\htdocs\project\index.php on line 58 Array
      【解决方案3】:

      您可以在 '/' 上拆分字符串并使用 array_pop 从结果数组中弹出每个项目:

      $str = "Home/Gallery/Images/Mountains";
      $bits = explode("/", $str);
      // Gives: 
      Array
      (
        [0] => Home
        [1] => Gallery
        [2] => Images
        [3] => Mountains
      )
      
      $last = array_pop($bits);
      echo 'last: ' .$last; // Mountains
      
      $next = array_pop($bits);
      echo 'next: ' .$next; // Images
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        • 2012-12-26
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        相关资源
        最近更新 更多