Search code examples
phppreg-match

How can I get the current web directory from the URL?


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/


Solution

  • Use the dirname function like this:

    $dir =  dirname($_SERVER['PHP_SELF']);
    $dirs = explode('/', $dir);
    echo $dirs[0]; // get first dir