...

View Full Version : Returning URI segments



macleodjb
04-29-2009, 11:38 PM
Hi Guys,

I was curious if i have a url like this.

www.example.com/dir/bob/photos

is there a way i can isolate the parts of the url by calling them specifically.

like this.
uri($path, 3) = photos
uri($path, 1) = dir

Thanks in advance.

timgolding
04-30-2009, 12:31 AM
yes many ways one such way is to explode (http://uk.php.net/manual/en/function.explode.php)them into an array:



<?php
$path="http://www.example.com/dir/bob/photos";
$segments=explode("/", $path);

//display first segment
echo $segments[0]; // Note first allways start with index 0

//display second
echo $segments[1];

//display last
echo $segments[count[$segment]-1]; // Note because indexes start at 0 have to deduct one from count function

// loop through all segments
foreach($segments $key => $value)
{
echo "segment". $key . "=" . $value ."<br />";
}
?>


There are other things you can do with regex to remove the domain part of the url.

In my example though the first would be http:
the second would be NULL
The third would be www.example.com
and so on
The last would be photos.

In your example www.example.com/dir/bob/photos
the first would be www.example.com
the second dir
etc

timgolding
04-30-2009, 12:39 AM
If you want to get the full url path to the page you are in you can use


$path=$_SERVER['PHP_SELF'];


There are other example of similar things you can get about the script you are in here http://uk.php.net/manual/en/reserved.variables.server.php

kbluhm
04-30-2009, 06:35 AM
Here's a stripped down snippet from a CMS I have written:


/*
* segments ( [ int $index = NULL ] ) -> string
*/

function segments( $index = NULL )
{
static $segments;
// build $segments on first function call
if ( NULL === $segments )
{
$segments = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$segments = explode( '/', $segments );
$segments = array_filter( $segments );
$segments = array_values( $segments );
}
// if $index is NULL, emulate REQUEST_URI
if ( NULL === $index )
{
return '/' . implode( '/', $segments );
}
// return the segment index if valid, otherwise NULL
$index = ( int ) $index - 1;
return isset( $segments[$index] ) ? $segments[$index] : NULL;
}




// URI: /this/is//a/path/to///nothing
echo segments( 4 ); // path
echo segments( 18 ); // NULL
echo segments(); // /this/is/a/path/to/nothing



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum