如何在PHP中正确分割路径 [英] How to split a path properly in PHP

查看:71
本文介绍了如何在PHP中正确分割路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作的最佳方法是什么?

What is the best way to do the following:

我得到一个带有AJAX请求的路径

I get a path with an AJAX request

例如dir1/dir2/dir3/dir4

我需要在我的网页上这样显示它:

I need to present it like this on my webpage:

dir1 >> dir2 >> dir3 >> dir4

每个都是html锚标签,href属性为

each of them being html anchor tags with the href attribute being

/dir1

/dir1/dir2

/dir1/dir2/dir3

/dir1/dir2/dir3/dir4 

分别

实现这一目标的最优雅,最有效的方法是什么?

What is the most elegant and efficient way to achieve this?

到目前为止,我正在做这样的事情,我认为它确实很脏:

so far, I'm doing something like this which i think is really dirty:

<?php 
$dirs = explode(PATH_SEPARATOR, $this->metadata["path"]);
    foreach ($dirs as $key=>$val) {
             if ($val == '') {
                 continue;
             }
             $pathArray = array();
             for ($i = 0; $i <= $key; $i++) {
                 array_push($pathArray, $dirs[$i]);
             }
             $path = implode('/', $pathArray);
             echo " >> <a href=" . $path . ">" . truncate($val) . "</a>";
    }
    ?>  

推荐答案

可能是这样的事情(如果我正确理解了您的意图):

Something like this maybe (if I got your intention right):

<?php
$str = 'dir1/dir2/dir3/dir4';

$output = array();
$chunks = explode('/', $str);
foreach ($chunks as $i => $chunk) {
    $output[] = sprintf(
        '<a href="#/%s">%s</a>',
        implode('/', array_slice($chunks, 0, $i + 1)),
        $chunk
    );
}

echo implode(' &gt;&gt; ', $output);

输出:

<a href="#/dir1">dir1</a> &gt;&gt; 
<a href="#/dir1/dir2">dir2</a> &gt;&gt;
<a href="#/dir1/dir2/dir3">dir3</a> &gt;&gt;
<a href="#/dir1/dir2/dir3/dir4">dir4</a>

这篇关于如何在PHP中正确分割路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆