如何从URL获取当前的Web目录?
If I have a URL that is http://www.example.com/sites/dir/index.html, I would want to extract the word "sites". I know I have to use regular expressions but for some reason my knowledge of them is not working on PHP.
I am trying to use :
$URL = $_SERVER["REQUEST_URI"];
preg_match("%^/(.*)/%", $URL, $matches);
But I must be doing something wrong. I would also like it to have a catch function where if it is at the main site, www.example.com then it would do the word "MAIN"
Edit: sorry, I've known about dirname...It gives the full directory path. I only want the first directory.... So if its www.example.com/1/2/3/4/5/index.html then it returns just 1, not /1/2/3/4/5/
如果我的网址 http://www.example.com/sites/dir/index.html ,我想提取”网站“这个词。 我知道我必须使用正则表达式,但由于某种原因,我对它们的了解不适用于PHP。 p>
我正在尝试使用: p>
$ URL = $ _SERVER [“REQUEST_URI”];
preg_match(“%^ /(。*)/%”,$ URL,$ matches);
code> pre>
\ n 但我一定做错了。 我还希望它有一个catch函数,如果它在主站点www.example.com然后它会做“MAIN”这个词 p>
编辑:对不起,我' 我知道dirname ...它给出了完整的目录路径。 我只想要第一个目录......所以如果它是www.example.com/1/2/3/4/5/index.html那么它只返回1,而不是/ 1/2/3 / 4/5 / p>
div>
Use the dirname
function like this:
$dir = dirname($_SERVER['PHP_SELF']);
$dirs = explode('/', $dir);
echo $dirs[0]; // get first dir
The dirname function should get you what you need
http://us3.php.net/manual/en/function.dirname.php
<?php
$URL = dirname($_SERVER["REQUEST_URI"]);
?>
Just wanted to recommend additionally to check for a prefixed "/" or "\" and to use DIRECTORY_SEPARATOR :
$testPath = dirname(__FILE__);
$_testPath = (substr($testPath,0,1)==DIRECTORY_SEPARATOR) ? substr($testPath,1):$testPath;
$firstDirectory = reset( explode(DIRECTORY_SEPARATOR, dirname($_testPath)) );
echo $firstDirectory;
A simple and robust way is:
$currentWebDir = substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));
If you are worried about DIRECTORY_SEPARATORS, you could also do:
$currentWebDir = str_replace('\\', '/', substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT'])));
Also be aware of mod_rewrite issues mentioned by FrancescoMM