How to parse URL and get URI segment in PHP

803

How to parse url and get URI segment in PHP

In this quick post I’ll will show you How to parse url and get URI segment in PHP, The URL segments are used for many purposes in the web based application. for parsing URL segment easily you can use parse_url() function in PHP. Below I’ll show you the basic example to get first , second and last URI segments using PHP.

parse_url() – This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

Parsing URL and get URI segment in PHP

Use following code to get each segment/component of the URL.

$exampleURL = "https://latestblog.org/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