views:

29

answers:

3

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/

A: 

The dirname function should get you what you need

http://us3.php.net/manual/en/function.dirname.php

<?php
    $URL = dirname($_SERVER["REQUEST_URI"]);
?>
Levi Hackwith
A: 

Use the dirname function like this:

$dir =  dirname($_SERVER['PHP_SELF']);
$dirs = explode('/', $dir);
echo $dirs[0]; // get first dir
Sarfraz
Please look at my edit.
BHare
@Brian: See my updated answer please.
Sarfraz
A: 

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];
Gumbo