PHP拆分URL来创建"你在这里"导航

时间:2015-01-30 16:33:55

标签: php

获取此页面"您在这里"它将阅读以下内容;

  

HOME => questions => 28240416 => PHP的分裂URL到创造 - 你 - 是 - 这里的导航

我想使用PHP来获取URL并在域名分隔后通过正斜杠' /'创造一个"你在这里"内容。

此外,我想更换所有' - ',' _','%20'用' '并将分裂的第一个字母大写。

模拟网址示例;

网址:https://stackoverflow.com/users/4423554/tim-marshall

会回来;

  

首页=>用户=> 4423554 => TIM-马歇尔

我的最新尝试

我的最新尝试只生成字符串的最后一部分;

<?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;
?>

2 个答案:

答案 0 :(得分:1)

使用explodearray_unshiftarray_mapucfirstimplode

$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(
    ' =&gt; ',
    array_map(function($item) { return ucfirst($item); }, $parts)
); // Capitalize and glue together with =>

输出:

Home =&gt; This =&gt; Is =&gt; The =&gt; 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)

答案 1 :(得分:0)

实施例

<?php
    $url = "testdomain.com/Category/Sub-Category/Files.blah";;
    $chunks = array_filter(explode('/', $url));
    echo "<h1>".implode(' &gt;&gt; ', $chunks)."</h1>";
?>

用法:

对于您当前的页面,请替换

$url = "testdomain.com/Category/Sub-Category/Files.blah";

使用

$url = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

它会返回你的“你在哪里”导航。