要获得此页面"You are here",它将阅读以下内容;
主页 => 问题 => 28240416 => php-split-url-to-create-you-are-here-navigation
我想使用 PHP 获取 URL 并在域名后拆分,通过正斜杠"/"分隔所有内容以创建"您在这里"的内容。
此外,我想将所有"-","_","%20"替换为",并将拆分的第一个字母大写。
模拟网址示例;
网址: https://stackoverflow.com/users/4423554/tim-marshall
会回来;
首页 =>用户 => 4423554 => 蒂姆-马歇尔
我的最新尝试
我最近的尝试只产生了字符串的最后一部分;
<?php
$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";;
$parts = explode('/', rtrim($url, '/'));
$id_str = array_pop($parts);
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
echo '<h1>'.$id_str.'</h1>';
?>
又一次尝试
<?php
$url = 'somedomainDOTcom/animals/dogs';
$arr = explode($url, '/');
unset($arr[0]);
$title = '';
foreach($arr as $v) $title .= ucfirst($v).'>>';
$title =trim($title,'>');
echo "'n<br>".$title;
?>
使用 explode
、 array_unshift
、array_map
、ucfirst
和 implode
:
$url = '/this/is/the/path'; // or $_SERVER['REQUEST_URI'].. avoid $_SERVER['HTTP_HOST']
$url = str_replace(array('-', '_', '%20'), ' ', $url); // Remove -, _, %20
// your choice of removing extensions goes here
$parts = array_filter(explode('/', $url)); // Split into items and discard blanks
array_unshift($parts, 'Home'); // Prepend "Home" to the output
echo implode(
' => ',
array_map(function($item) { return ucfirst($item); }, $parts)
); // Capitalize and glue together with =>
输出:
Home => This => Is => The => Path
或在解析的 HTML 中:
Home => This => Is => The => Path
如果 URI 中有杂散点,则删除扩展是更棘手的部分。如果保证只有文件名才会有点,则可以使用:
$url = explode('.', $url);
$url = $url[0]; // Returns the left half
但是,如果没有保证,并且您知道可能的扩展是什么,则可以再次使用str_replace
:
$url = str_replace(array('.php','.html','.whatever'), '', $url);
但是由于您只打算在PHP上下文中运行此脚本,因此它可能像以下那样简单:
$url = str_replace('.php', '', $url)
示例:
<?php
$url = "testdomain.com/Category/Sub-Category/Files.blah";;
$chunks = array_filter(explode('/', $url));
echo "<h1>".implode(' >> ', $chunks)."</h1>";
?>
用法:
对于当前页面,请替换
$url = "testdomain.com/Category/Sub-Category/Files.blah";
跟
$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
它将返回您的"你在哪里"导航。