For those of you who use CMS, such as WordPress or Magento, that add a trailing slash, there is a simple addition to Vasil's solution:
<?php $url = "http://example.com/i/am/file.php"; $keys = parse_url($url); // parse the url $path = explode("/", $keys['path']); // splitting the path $last = end($path); // get the value of the last element $last = prev($path); // get the next to last element ?>
You can even just use a simple call URI request like this:
$request_path = $_SERVER['REQUEST_URI']; $path = explode("/", $request_path); // splitting the path $last = end($path); $last = prev($path);
source share