Forum Moderators: coopster

Message Too Old, No Replies

Identifying parts of a string

Difficult to explain

         

Richie0x

1:01 pm on May 5, 2004 (gmt 0)

10+ Year Member



$url = /blah/elephant/spaghetti/page.php

This gives you the whole path.

But how can you identify each directory in the url individually?

ie. I want $one to equal 'blah', $two to equal 'elephant' etc.

Lawbreak

1:24 pm on May 5, 2004 (gmt 0)

10+ Year Member




Easiest thing is to convert it into an array:

$url = "/blah/elephant/spaghetti/page.php";
$urlarray=explode("/",$url);

Result:
Array ( [0] => [1] => blah [2] => elephant [3] => spaghetti [4] => page.php )

coopster

1:55 pm on May 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You could also employ the PHP dirname [php.net] function to get rid of the filename component of the path before you explode [php.net] it...
$path = '/blah/elephant/spaghetti/page.php'; 
$dirs = explode('/', dirname($path));
/* returns...
Array
(
[0] =>
[1] => blah
[2] => elephant
[3] => spaghetti
)
*/

Also, if this truly will be a url, you may want to have a look at parse_url() [php.net].

And hey Lawbreak, welcome to WebmasterWorld!

Lawbreak

2:00 pm on May 5, 2004 (gmt 0)

10+ Year Member



Good suggestions Coopster, and thanks for the welcome. I'm a longtime lurker, but finally decided to try to return the favor.

coopster

2:09 pm on May 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You offered the advice, I merely added on. Thanks for the contribution. It's nice to see you move from lurker to contributor :)

Richie0x

7:34 pm on May 5, 2004 (gmt 0)

10+ Year Member



Thanks guys :)

How do you work out how many directories are in the url?

Netizen

7:44 pm on May 5, 2004 (gmt 0)

10+ Year Member



You probably want to strip out the empty first part of

$dirs=explode('/',pathname($url));

you could do something like

$dirs=explode('/',substr(pathname($url),1));

then print_r($dirs) would give you

Array
(
[0] => blah
[1] => elephant
[2] => spaghetti
)

But then to find out the number of levels just do

$levels=count($dirs);