简单的动态痕迹导航

2022-08-30 17:57:39

我认为这个脚本对这里的任何新手都有很大的兴趣:)包括我:)

我想创建的是一个小代码,我可以在任何文件中使用,并将生成如下痕迹导航:

如果文件名为“website.com/templates/index.php”,则痕迹导航应显示:

Website.com > Templates

^^链接^^说明文本

如果文件名为“website.com/templates/template_some_name.php”,则痕迹导航应显示:

Website.com > Templates > Template Some Name

^^链接^^链接^^说明文本


答案 1

对于一个简单的面包屑来说,这可能有些过分,但值得一试。我记得很久以前当我第一次开始时遇到这个问题,但我从来没有真正解决过它。也就是说,直到我决定现在写这个。:)

我已经尽我所能内联记录了,底部有3个可能的用例。享受!(随时询问您可能遇到的任何问题)

<?php

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' &raquo; ', $home = 'Home') {
    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>");

    // Find out the index for the last value in our path array
    $last = end(array_keys($path));

    // Build the rest of the breadcrumbs
    foreach ($path AS $x => $crumb) {
        // Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
        $title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));

        // If we are not on the last index, then display an <a> tag
        if ($x != $last)
            $breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
        // Otherwise, just display the title (minus)
        else
            $breadcrumbs[] = $title;
    }

    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs);
}

?>

<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>

答案 2

嗯,从你给出的例子来看,这似乎是“$_SERVER['REQUEST_URI']”,explode()函数可以帮助你。您可以使用分解将域名后面的 URL 分解为一个数组,在每个正斜杠处将其分隔开来。

作为一个非常基本的例子,可以实现这样的东西:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}

推荐