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
Use the dirname
function like this:
$dir = dirname($_SERVER['PHP_SELF']);
$dirs = explode('/', $dir);
echo $dirs[0]; // get first dir
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
Use parse_url to get the path from $_SERVER['REQUEST_URI']
and then you could get the path segments with explode:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1));
echo $segments[1];
The dirname function should get you what you need
http://us3.php.net/manual/en/function.dirname.php
<?php
$URL = dirname($_SERVER["REQUEST_URI"]);
?>