Intereting Posts

Простая динамическая пачка

Я думаю, что этот сценарий представляет большой интерес для любого нуба здесь :), включая меня 🙂

То, что я хочу создать, – это небольшой код, который я могу использовать в любом файле, и создаст такую ​​палитру:

Если файл называется « website.com/templates/index.php », пакетная строка должна показать:

Website.com > Templates 

^^ link ^^ простой текст

Если файл называется « website.com/templates/template_some_name.php », в палитре должна отображаться:

 Website.com > Templates > Template Some Name 

^^ link ^^ link ^^ простой текст

    Хм, из приведенных вами примеров кажется «$ _SERVER ['REQUEST_URI] ), и функция explode () может вам помочь. Вы можете использовать explode для разложения URL-адреса, следующего за доменным именем, в массив, разделяя его при каждом обратном косе.

    В качестве очень простого примера можно было бы сделать что-то подобное:

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

    Это может быть излишним для простой сухари, но это стоит того. Я помню этот вопрос давно, когда я только начинал, но я никогда не решал его. То есть, пока я просто не решил написать это сейчас. 🙂

    Я задокументировал как можно лучше, внизу – 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> 

    Также сделал небольшой скрипт с использованием RDFa (вы также можете использовать микроданные или другие форматы). Проверьте это на google. Этот скрипт также учитывает структуру вашего сайта.

     function breadcrumbs($text = 'You are here: ', $sep = ' &raquo; ', $home = 'Home') { //Use RDFa breadcrumb, can also be used for microformats etc. $bc = '<div xmlns:v="http://rdf.data-vocabulary.org/#" id="crums">'.$text; //Get the website: $site = 'http://'.$_SERVER['HTTP_HOST']; //Get all vars en skip the empty ones $crumbs = array_filter( explode("/",$_SERVER["REQUEST_URI"]) ); //Create the home breadcrumb $bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$home.'</a>'.$sep.'</span>'; //Count all not empty breadcrumbs $nm = count($crumbs); $i = 1; //Loop the crumbs foreach($crumbs as $crumb){ //Make the link look nice $link = ucfirst( str_replace( array(".php","-","_"), array(""," "," ") ,$crumb) ); //Loose the last seperator $sep = $i==$nm?'':$sep; //Add crumbs to the root $site .= '/'.$crumb; //Make the next crumb $bc .= '<span typeof="v:Breadcrumb"><a href="'.$site.'" rel="v:url" property="v:title">'.$link.'</a>'.$sep.'</span>'; $i++; } $bc .= '</div>'; //Return the result return $bc;} 

    используйте parse_url а затем выведите результат в цикле:

     $urlinfo = parse_url($the_url); echo makelink($urlinfo['hostname']); foreach($breadcrumb in $urlinfo['path']) { echo makelink($breadcrumb); } function makelink($str) { return '<a href="'.urlencode($str).'" title="'.htmlspecialchars($str).'">'.htmlspecialchars($str).'</a>'; } 

    (Псевдокод)

    Я начал с кода Dominic Barnes, включил обратную связь от cWoDeR, и у меня все еще были проблемы с панировочными сухарями на третьем уровне, когда я использовал подкаталог. Поэтому я переписал его и включил код ниже.

    Обратите внимание, что я настроил свою структуру веб-сайта таким образом, чтобы страницы, подчиненные (связанные с) страницей на корневом уровне, настраивались следующим образом:

    • Создайте папку с таким же именем EXACT, как и файл (включая заглавные буквы), за вычетом суффикса, как папку на корневом уровне

    • поместите все подчиненные файлы / страницы в эту папку

    (например, если хотите сориентировать страницы для Customers.php:

    • создайте папку под названием Customers на том же уровне, что и Customer.php

    • добавьте файл index.php в папку Customers, которая перенаправляет на вызывающую страницу для папки (см. ниже для кода)

    Эта структура будет работать для нескольких уровней подпапок.

    Просто убедитесь, что вы следуете описанной выше структуре файлов И вставьте файл index.php с кодом, указанным в каждой подпапке.

    Код на странице index.php в каждой подпапке выглядит так:

     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Redirected</title> </head> <body> <?php $root_dir = "web_root/" ; $last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ; $path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; header('Location: '.$path_to_redirect) ; ?> </body> </html> 

    Если вы используете корневой каталог сервера в качестве своего веб-корня (т. Е. / Var / www / html), тогда установите $ root_dir = "": (не оставляйте конечный «/»). Если вы используете подкаталог для своего веб-сайта (т. Е. / Var / www / html / web_root, тогда установите $ root_dir = "web_root /"; (замените web_root фактическим именем вашего веб-каталога) (обязательно включите трейлинг /

    во всяком случае, вот мой (производный) код:

     <?php // Big Thank You to the folks on StackOverflow // See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb // Edited to enable using subdirectories to /var/www/html as root // eg, using /var/www/html/<this folder> as the root directory for this web site // To enable this, enter the name of the subdirectory being used as web root // in the $directory2 variable below // Make sure to include the trailing "/" at the end of the directory name // eg use $directory2="this_folder/" ; // do NOT use $directory2="this_folder" ; // If you actually ARE using /var/www/html as the root directory, // just set $directory2 = "" (blank) // with NO trailing "/" // 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 sets the subdirectory as web_root (If you want to use a subdirectory) // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /) $directory2 = "web_root/" ; // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ; $path_array = array_filter(explode('/',$path)) ; // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root // This removes the first item in the array path so it doesn't repeat if ($directory2 != "") { array_shift($path_array) ; } // This will build our "base URL" ... Also accounts for HTTPS :) $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ; // 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>") ; // Get the index for the last value in our path array $last = end($path_array) ; // Initialize the counter $crumb_counter = 2 ; // Build the rest of the breadcrumbs foreach ($path_array as $crumb) { // Our "title" is the text that will be displayed representing the filename without the .suffix // If there is no "." in the crumb, it is a directory if (strpos($crumb,".") == false) { $title = $crumb ; } else { $title = substr($crumb,0,strpos($crumb,".")) ; } // If we are not on the last index, then create a hyperlink if ($crumb != $last) { $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ; $calling_page_path = "/".implode('/',$calling_page_array).".php" ; $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ; } // Otherwise, just display the title else { $breadcrumbs[] = $title ; } $crumb_counter = $crumb_counter + 1 ; } // 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> ?> 

    Привет, Доминик, ваш ответ был приятным, но если у вас есть такой сайт, как http: //localhost/project/index.php, ссылка «проект» повторяется, так как она является частью $ base и также появляется в массиве $ path. Поэтому я изменил и удалил первый элемент в массиве $ path.

     //Trying to remove the first item in the array path so it doesn't repeat array_shift($path); 

    Я не знаю, является ли это самым элегантным способом, но теперь он работает для меня.

    Я добавляю этот код до этого в строке 13 или что-то еще

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

    Вот большая простая динамическая паника (настройка по мере необходимости):

      <?php $docroot = "/zen/index5.php"; $path =($_SERVER['REQUEST_URI']); $names = explode("/", $path); $trimnames = array_slice($names, 1, -1); $length = count($trimnames)-1; $fixme = array(".php","-","myname"); $fixes = array(""," ","My<strong>Name</strong>"); echo '<div id="breadwrap"><ol id="breadcrumb">'; $url = ""; for ($i = 0; $i <= $length;$i++){ $url .= $trimnames[$i]."/"; if($i>0 && $i!=$length){ echo '<li><a href="/'.$url.'">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</a></li>'; } elseif ($i == $length){ echo '<li class="current">'.ucfirst(str_replace($fixme,$fixes,$trimnames[$i]) . ' ').'</li>'; } else{ echo $trimnames[$i]='<li><a href='.$docroot.' id="bread-home"><span>&nbsp;</span></a></li>'; } } echo '</ol>'; ?> 

    Лучше использовать функцию explode() следующим образом …

    Не забудьте заменить вашу переменную URL в гиперссылке href .

     <?php if($url != ''){ $b = ''; $links = explode('/',rtrim($url,'/')); foreach($links as $l){ $b .= $l; if($url == $b){ echo $l; }else{ echo "<a href='URL?url=".$b."'>".$l."/</a>"; } $b .= '/'; } } ?>