2010-12-07 20 views
0

我還在學習php。你如何提取根目錄?

'SCRIPT_FILENAME' => string 'D:/Project Storage/wnmp/www/folder/index.php' (length=45) 
'SCRIPT_NAME'  => string '/folder/index.php' (length=18) 
'DOCUMENT_URI' => string '/folder/index.php' (length=18) 
'PHP_SELF'  => string '/folder/index.php' (length=18) 
'REQUEST_URI'  => string '/folder/helloworld/helloworldtwo/etc' (length=15) 

,你可以看到,我只是想獲得helloworld/helloworldtwo/etc

任何想法解壓文件夾?所以它會是helloworld/helloworldtwo/etc

即時通訊的想法是即時定義我的文件夾,如$root = 'folder'。那麼我提取它,如果它匹配,但問題是什麼?

第二個想法是從php_self或任何上面得到第一個從/first/second.php, 但我不知道最好的方式來做到這一點。

另一個問題是當我們在前面有兩個文件夾時?順便說一句,感謝所有的重播,即時通訊仍然在做一些閱讀php.net,測試,並嘗試。

'SCRIPT_FILENAME' => string 'D:/Project Storage/wnmp/www/folder/index.php' (length=45) 
'SCRIPT_NAME'  => string '/folder/folder2/index.php' (length=18) 
'DOCUMENT_URI' => string '/folder/folder2/index.php' (length=18) 
'PHP_SELF'  => string '/folder/folder2/index.php' (length=18) 
'REQUEST_URI'  => string '/folder/folder2/helloworld/helloworldtwo/etc' (length=15) 

的問題還是一樣的我怎樣才能將HelloWorld/hellowrodltwo /等的正確途徑。

編輯* 謝謝你們了很多我做了一個解決方案

$str = 'folder/folder/helloworld/helloworldtwo/etc'; 
$folder = 'folder/folder'; 
$q = str_replace($folder, NULL, $str); 
echo $q; 

,但如果有什麼/替代或更好的方式來做到這一點,請做。

再次感謝。

+1

你看過[parse_url](http://php.net/manual/en/function.parse-url.php)和[pathinfo](http:// uk3。 php.net/manual/en/function.pathinfo.php) - 和它們相關的函數(如基本名稱等)? – Mike 2010-12-07 13:27:43

回答

2

問題,您可以使用爆炸功能在PHP

$str = 'folder/helloworld/helloworldtwo/etc'; 

print_r(explode('/', $str, 2)); 

輸出將是:

Array 
(
    [0] => folder 
    [1] => helloworld/helloworldtwo/etc 
) 

如果你有多個文件夾/你能做到使用'文件夾/'作爲分隔符並且沒有施加限制

$str = 'folder/folder/helloworld/helloworldtwo/etc'; 

print_r(explode('folder/', $str)); 

輸出將是:

array (
    0 => '', 
    1 => '', 
    2 => 'helloworld/helloworldtwo/etc', 
) 

,那麼你可以使用破滅功能的加入它放回一個字符串

$returnValue = implode('', array (
    0 => '', 
    1 => '', 
    2 => 'helloworld/helloworldtwo/etc', 
)); 

加入這2個功能,你可以從URL中移除你要多少文件夾和有乾淨的網址在一個字符串末尾

+0

如果我有兩個文件夾怎麼樣?編輯了這個問題。 – 2010-12-07 13:49:41

1

如果你知道它永遠是"/folder/"你想刪除,那麼你可以使用類似:

$extracted = str_replace("/folder/","",$_SERVER['REQUEST_URI'],1); 

這是什麼所行它取代的/folder/所有出現與和空字符串。這會給使用URL如/folder/helloworld/folder/helloworld2

+0

重要提示:斜槓應始終位於字符串內,否則可能會導致問題。 – RobertPitt 2010-12-07 13:44:17