【发布时间】:2019-10-17 13:19:39
【问题描述】:
我创建了一个面包屑菜单,它获取页面 URL,explodes 每个尾部斜杠(在域之后)之后的文本并将其打印出来。
如果没有向 URL 添加查询字符串,这会正常工作,但是,一旦添加了查询,它就会复制链接:
工作示例:
<?php
$url = "/parent/child";
// 1. Get URL
$crumbs = explode("/", trim($url, '/'));
// 2. Strip extras
$build = '';
// 3. Define int so last item is not a link
$lastKey = count($crumbs) - 1;
// 4. Execute loop
foreach($crumbs as $key => $crumb){
$build .= '/'.$crumb;
// format text
$crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
$crumb = preg_replace('/-/', ' ', $crumb); // remove dashes
$crumb = trim($crumb); // remove whitespace from before and after string
$pagename = "child";
echo $key < $lastKey
? "$crumb /" : $pagename;
}
?>
以上输出:父/子
这很好。
但是,现在使用查询字符串进行第二个测试(注意$url):
<?php
$url = "/parent/child/?=query-string";
// 1. Get URL
$crumbs = explode("/", trim($url, '/'));
// 2. Strip extras
$build = '';
// 3. Define int so last item is not a link
$lastKey = count($crumbs) - 1;
// 4. Execute loop
foreach($crumbs as $key => $crumb){
$build .= '/'.$crumb;
// format text
$crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
$crumb = preg_replace('/-/', ' ', $crumb); // remove dashes
$crumb = trim($crumb); // remove whitespace from before and after string
$pagename = "parent";
echo $key < $lastKey
? "$crumb /" : $pagename;
}
?>
这输出:父/子/父 预期输出:**父/子**
我知道我设置了$pagename = "parent",但我希望它忽略查询字符串。
我尝试了以下方法:
$crumbs = explode("/", trim($_SERVER["REQUEST_URI"], '/'));
$crumbs = preg_replace('/\?.*/', '', $crumbs);
还是一样的结果。
最新代码:
<?php
// 1. Get current URL
$crumbs = trim($_SERVER["REQUEST_URI"]);
$crumbs = preg_replace('/\?.*/', '', $crumbs);
$crumbs = explode("/", $crumbs);
array_filter($crumbs);
$count = count($crumbs);
$build = '';
// 3. Define int so last item is not a link
$lastKey = count($crumbs) - 1;
// 4. Execute loop
foreach($crumbs as $key => $crumb){
$build .= $crumb;
// format text
$crumb = ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
$crumb = preg_replace('/-/', ' ', $crumb); // remove dashes
$crumb = trim($crumb); // remove whitespace from before and after string
$pagename = get_query_var('pagename');
$pagename = the_title('', '', false); // print page name as is in WP
$pagename = preg_replace('/-/', ' ', $pagename); // remove dashes
$pagename = trim($pagename);
echo $key < $lastKey
? "<a class='crumbLink' href=".$build.">".$crumb."</a>
<span class='slash'>/</span>"
: $pagename;
}
?>
【问题讨论】:
标签: php regex breadcrumbs