2012-05-18 81 views
4

如果我有一個網址,例如www.example.com/test/example/product.html請求URI PHP:獲得第一級

我如何將能夠得到公正的測試部分(所以頂層)

我知道你會用$_SERVER['REQUEST_URI']也許substrtrim

但我不確定如何做到這一點,謝謝!

回答

15

將該字符串拆分爲一個數組,並將其替換爲explode,然後取出需要的部分。

$whatINeed = explode('/', $_SERVER['REQUEST_URI']); 
$whatINeed = $whatINeed[1]; 

如果你使用PHP 5.4,你可以做$whatINeed = explode('/', $_SERVER['REQUEST_URI'])[1];。 :)

+0

好的答案在這裏 –

+0

感謝您指出這一點。複製/粘貼ftw。 :D –

+3

不應該是$ whatINeed [1]? $ _SERVER ['REQUEST_URI']以斜槓開頭,結果是第一個URI級別在[1]中而不是[0]。 – CodeX

4
<?php 
$url = 'http://username:[email protected]/test/example/product.html?arg=value#anchor'; 

print_r(parse_url($url)); 

$urlArray = parse_url($url); 

/* Output: 

Array 
(
    [scheme] => http 
    [host] => hostname 
    [user] => username 
    [pass] => password 
    [path] => /test/example/product.html 
    [query] => arg=value 
    [fragment] => anchor 
) 


*/ 

echo dirname($urlArray[path]); 

/* Output: 

/test  

*/ 
+1

嗯,使用parse_url的想法是好的,但dirname將返回「/ text/example」 - 整個dirname。它只上升一級。 –

+0

良好的捕獲,你要麼必須餵它多次自己或使用爆炸(只是注意跨操作系統的問題) – Incognito