【发布时间】:2020-08-15 16:15:10
【问题描述】:
路径:
Home/Gallery/Images/Mountains
此路径中的最后一个文件夹名称是 Mountains,倒数第二个文件夹名称是 Images。
我想显示这个输出:
Last folder: Mountains
Second last folder: Images
是否可以使用 substr 或任何其他方式。这里有谁能给我答案吗?谢谢
【问题讨论】:
路径:
Home/Gallery/Images/Mountains
此路径中的最后一个文件夹名称是 Mountains,倒数第二个文件夹名称是 Images。
我想显示这个输出:
Last folder: Mountains
Second last folder: Images
是否可以使用 substr 或任何其他方式。这里有谁能给我答案吗?谢谢
【问题讨论】:
只需 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_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
【讨论】: