Bu deneyin:
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']);
Ben de yorumlarından birkaç URL'leri ile test ettik. / Bob bir dizin veya dosya olup olmadığını tespit edemez, çünkü tüm yollar bir çizgiyle sona varsaymak zorunda gidiyorum. Bu da bir bölü olan sürece bir dosya olduğunu varsayalım.
echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce
echo getLastPathSegment('http://server.com/bla/wce/'); // wce
echo getLastPathSegment('http://server.com/bla/wce'); // bla