uri_part: A PHP Function for Working with the Current URI

main

A PHP function that makes it extremely easy to display dynamic content within your existing Content Management System (CMS), web application framework or standard "PHP-enabled" website.

function uri_part($n) {
	$path = explode("/", $_SERVER["REQUEST_URI"]);
	for ($i = 0; $i <= count($path); $i++) {
		if(is_null($path[$i]) || $path[$i] == "") {
			unset($path[$i]);
		}
	}
	$path = array_values($path);
	switch($n) {
		case 0: return @$path[0]; break;
		case 1: return @$path[1]; break;
		case 2: return @$path[2]; break;
		case 3: return @$path[3]; break;
	}
}

Usage Examples

Below are examples of how this function can be used in a template file such as the header.php file from your WordPress install or the page.tpl.php file from your Drupal install.

Example 1

if (uri_part(0)) {
	echo "Hello part 0";
}	

Example 2

<title><?php
if (uri_part(0)) {
	echo "Homepage Title";
}
elseif (uri_part(1)) {
	echo uri_part(1);
}
?></title>

Example 3

if (uri_part(2) == "some-category") {
	echo '<ul id="silo">';
	echo '<li><a href="#">Silo Link 1</a></li>';
	echo '<li><a href="#">Silo Link 2</a></li>';
	echo '<li><a href="#">Silo Link ...</a></li>';
	echo '</ul>';
}
if (uri_part(2) == "some-other-category") {
	echo '<ul id="silo">';
	echo '<li><a href="#">Other Silo Link 1</a></li>';
	echo '<li><a href="#">Other Silo Link 2</a></li>';
	echo '<li><a href="#">Other Silo Link ...</a></li>';
	echo '</ul>';
}