How to parse URL and get URI segment in PHP

<?php
$exampleURL = "http://iamrohit.in/category/php/hello-world";
$uriSegments = explode("/", parse_url($exampleURL, PHP_URL_PATH));
echo "<pre>";
var_dump($getUriSegments);
 
You will see output like this.
array(4) { [0]=> string(0) "" [1]=> string(8) "category" [2]=> string(3) "php" [3]=> string(11) "hello-world" }

In the above example i am using static URL you can get current page url by replacing $exampleURL to $_SERVER[‘REQUEST_URI’]

$getUriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

 
Now you got all the URI segment in associative array. extract any segment/component you want.

echo $uriSegments[1]; //returns category echo $uriSegments[2]; //returns php echo $uriSegments[3]; //returns hello-world

For getting last URI segment simply use array_pop() function in PHP.

$lastUriSegment = array_pop($uriSegments);
echo $lastUriSegment; //returns hello-world
 
Refrence: http://www.iamrohit.in/parse-url-get-uri-segment-php/ 

Comments

Popular posts from this blog

dynamic create multiple ckeditor onclick event using jquery

get lat and long from city name using jquery

membership registration and login system in php