PHP:Dumb URL到其目录

时间:2013-11-04 00:31:57

标签: php parsing url

我看到问题如何获取当前目录等问题,但我想采用绝对URL并从中删除文件(如果有文件 - 我必须能够接受没有它们的URL) 。所以,例如。

Original: http://www.example.com/index.html
New: http://www.example.com/

Original: http://www.example.com/dir/welcome/index.html
New: http://www.example.com/dir/welcome/

我无法弄清楚如何做到这一点,虽然这听起来很容易。任何指南,功能或解决方案?

1 个答案:

答案 0 :(得分:3)

您可以使用dirname(),并在没有文件时添加特殊情况

<?php
function getUrlDirectory($url) {
  return substr($url, -1) == '/' ? $url : dirname($url).'/';
}

$urls = array(
  'http://www.example.com/index.html',
  'http://www.example.com/dir/welcome/index.html',
  'http://www.example.com/no/file/',
);

foreach ($urls as $url) {
  echo getUrlDirectory($url)."\n";
}

运行时,它会给出:

$ php test.php 
http://www.example.com/
http://www.example.com/dir/welcome/
http://www.example.com/no/file/
相关问题