Note: you might find these PHP functions do what you are after as well Getting Path Information with PHP

This function is designed to return the file name called by a particular URL. It can also navigate up the URL to retrieve the parent directories if more of a path is needed in your application.

Syntax
getDirectory(targetURL:string, [noOfDirectories:int=0 ])

function getDirectory($full, $noDir=0){
	$pos1 = strripos($full, "/");
	$path = substr($full, $pos1);
	if($noDir == 0){
	    $path = str_replace("/", "", $path);
	}
	for($i=0;$i<$noDir;$i++){
 	   $slash1 = substr($full, 0, $pos1);
  	   $pos2 = strripos($slash1, "/");
  	   $slash2 = substr($slash1, $pos2);
  	   $path = $slash2 . $path;
  	   $full = $slash1;
   	   $pos1 = strripos($full, "/");
	}
	return $path;
}

The PHP function takes a URL as its first parameter. The second parameter is optional and represents the number of directories back up the URL you wish returned. If no second parameter is provided just the file name is returned.

For example given a URL of:

http://www.mustbebuilt.co.uk/wp-content/themes/basic/images/search.png

If we just want the file name “search.png” then we could call:

$origPath = "http://www.mustbebuilt.co.uk/wp-content/themes/basic/images/search.png";
$newPath = getDirectory($origPath);
echo $newPath;
//ouptut search.png

CodePad Demo

If you want the path including the two parent directories then the following call should be made:

$origPath = "http://www.mustbebuilt.co.uk/wp-content/themes/basic/images/search.png";
$newPath = getDirectory($origPath, 2);
echo $newPath;
//ouptut /basic/images/search.png

Notice the addition of the second parameter to the getDirectory() call.

Leave a Comment