2011-02-16 57 views
0

在PHP中,如何根據我所在的位置獲取網址相關指標?示例:如何獲得URL相對「深度」?

Location     Return 

example.com    ./ 
example.com/sub   ../ 
example.com/sub/sub  ../../ 

... 
+0

我可以問你想要的原因嗎? – Jacob 2011-02-16 00:50:35

+0

我使用一個包含PHP的頭文件來引用頂級樣式表和一個頂級菜單,而沒有消除實際頁面使用相對鏈接的可能性,因此不使用基礎href。 – Lazlo 2011-02-16 00:56:46

+0

絕對路徑可以使您的代碼更好,並結合環境常量,例如`define('BASE_URL','http://example.com/')`,並且仍然允許你使用親戚。 – Jacob 2011-02-16 01:04:41

回答

2

考慮到你上面的例子:

$url = 'example.com/sub/sub/'; 
$parts = explode('/', $url); 
$parts = array_filter($parts, 'strlen'); 
$path = count($parts) == 1 ? './' : str_repeat('../', count($parts)-1); 

此代碼忽略空的部分和結尾的斜槓(例如:example.com//sub/)。

1

不會只計算URL中的斜槓數量就足夠了。你可以使用preg_match_all

<?php 
preg_match_all('/\//',$url,$matches); 
echo count($matches); 
?> 

(未測試的代碼)

+2

不使用正則表達式。 `substr_count($ url,'/');` – Jacob 2011-02-16 00:52:53

1

嗯,咋的猜測:

function getDeepness($url){ 
    $lvls = substr_count($url, '/'); 

    if(!$lvls){ 
    return "./"; 
    } 

    return str_repeat("../", $lvls); 
}