2013-11-04 19 views
1

我看到問題如何獲取當前目錄等,但我想採取一個絕對的URL,並從中刪除文件(如果有一個文件 - 我必須能夠接受沒有他們的URL)。所以,例如。PHP:愚蠢的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/ 

我不知道如何做到這一點,儘管聽起來很簡單。任何指南,功能或解決方案?

回答

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/ 
+0

我知道parse_url的,但它的「路徑'收到目錄中包含的文件名,對吧? – BetaBlaze

+0

@BetaBlaze:對不起,我誤解了第二種情況,我編輯了我的回答 – Lepidosteus

+0

感謝您的幫助。 – BetaBlaze