tags:

views:

33

answers:

3

Hi guys, I had a little issue, i need to extract a string from the URL that looks like this:

http://www.myserver.com/category/firstcat/second-cat/

All my URLs has this structure, and I need to catch the "firstcat" string

I would appreciate your help!

Thanks so much!

+1  A: 

Get the path by parsing the URL, then explode it into the different components:

$urlinfo = parse_url('http://www.myserver.com/category/firstcat/second-cat/');
$parts = explode('/', trim($urlinfo['path'], '/'));
echo $parts[1]; // firstcat

If you're doing this on your own URL, use $_SERVER['PATH_INFO'] instead and skip parse_url() altogether:

$parts = explode('/', trim($_SERVER['PATH_INFO'], '/'));
echo $parts[1]; // firstcat
BoltClock
+1  A: 

Aren't you using mod_rewrite? Place a rule in your htaccess:

RewriteRule ([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)/ ?cat=$1&subcat=$2&name=$3

And you'll have it ready in $_GET array.

Tomasz Kowalczyk
+2  A: 

If you're trying to do this on the current url the user is on, you'll need $_SERVER['REQUEST_URI']. That will show you the current uri open, in this case /category/firstcat/second-cat/.

Then use anything you prefer to parse the string and get to the element you want, for example:

$elms = explode('/', $uri) ;
$firstcat = $elms[2] ;
Fanis