【问题标题】:Remove last child page from URI从 URI 中删除最后一个子页面
【发布时间】:2018-03-10 17:46:53
【问题描述】:

如何动态查找和删除网站路径 URI 的最后一个子项?

代码:$uri = $_SERVER["REQUEST_URI"];

结果:http://192.168.0.16/wordpress/blog/page-2/

想要的结果:http://192.168.0.16/wordpress/blog/

非常感谢!

【问题讨论】:

  • 但是博客会解析到第 2 页吗?最后一个孩子也是迂腐的http://192.168.0.16/wordpress/blog/

标签: php wordpress url path uri


【解决方案1】:

你可以使用它,你可以得到你需要的输出:

// implode string into array
$url = "http://192.168.0.16/wordpress/blog/page-2/";
//then remove character from right
$url = rtrim($url, '/');
// then explode
$url = explode('/', $url);
// remove the last element and return an array
json_encode(array_pop($url));
// implode again into string
echo implode('/', $url);

另一种方法是:

// implode string into array
$url = explode('/', 'http://192.168.0.16/wordpress/blog/page-2/');
//The array_filter() function filters the values of an array using a callback function.
$url = array_filter($url);
// remove the last element and return an array
array_pop($url);
// implode again into string
echo implode('/', $url);

【讨论】:

  • 你可以添加这个 $url = array_filter($url);
  • 您的第一种方法行不通。您必须修剪字符串,而不是数组
  • 感谢识别,写错了。 @Ravinder Reddy
【解决方案2】:

正确的方法是使用parse_url()dirname(),它们也将支持查询参数。你可以爆炸$uri['path'],但在这种情况下它是不必要的。

<?php
// explode the uri in its proper parts
$uri = parse_url('/wordpress/blog/page-2/?id=bla');

// remove last element
$path = dirname($uri['path']);

// incase you got query params, append them
if (!empty($uri['query'])) {
    $path .= '?'.$uri['query'];
}

// string(22) "/wordpress/blog?id=bla"
var_dump($path);

看看它的工作原理: https://3v4l.org/joJrF

【讨论】:

    【解决方案3】:
    $url = 'http://192.168.0.16/wordpress/blog/page-2/';
      // trim any slashes at the end
      $trim_url = rtrim($url,'/');
      // explode with slash
      $url_array = explode('/', $trim_url);
      // remove last element
      array_pop($url_array);
      // implade with slash
      echo $new_url = implode('/', $url_array); 
    

    输出:

    http://192.168.0.16/wordpress/blog
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多