The URL segments are used for many purposes in the web application. You can parse URL segments easily using the parse_url() function in PHP. Here we’ll provide the example code to get URI segments and the last URL segment using PHP.
Use the following code to get URL segments of the current URL. It returns all the segments of the current URL as an array.
$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
Usage:
When the current URL is http://www.example.com/codex/foo/bar
.
echo $uriSegments[1]; //returns codex
echo $uriSegments[2]; //returns foo
echo $uriSegments[3]; //returns bar
If you want to get last URI segment, use array_pop() function in PHP.
$lastUriSegment = array_pop($uriSegments);
echo $lastUriSegment; //returns bar