ankur140290
ankur140290

Reputation: 640

Get last URI segment excluding query string

I have an URL say: www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go. I want to extract the string register-car from it using php code. Please help.

Upvotes: 1

Views: 2035

Answers (4)

Gaʀʀʏ
Gaʀʀʏ

Reputation: 4540

You are looking for the parse_url function, followed by basename to return the last /item/. The following prints register-car.

  $parsed = parse_url("http://www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go", PHP_URL_HOST);
  echo basename($parsed['path']);

Upvotes: 0

Kelly Copley
Kelly Copley

Reputation: 3158

$parts = parse_url("www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go", PHP_URL_PATH);
$pieces = explode($parts, "/");
$action = $pieces[count($pieces)-1];

Upvotes: -1

Sherif
Sherif

Reputation: 11943

You can use a combination of parse_url and basename, or even pathinfo to help you with this.

In PHP < 5.4.7

$url = "www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go";
$result = basename(parse_url("http://" . $url, PHP_URL_PATH));
echo $result; // register-car

In PHP >= 5.4.7

$url = "www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go";
$result = basename(parse_url("//" . $url, PHP_URL_PATH));
echo $result; // register-car

Upvotes: 0

Viren Rajput
Viren Rajput

Reputation: 5746

try this:

<?php 

 $url = "www.abc.com/blog/2012/12/register-car?w=Search&searchDmv=Go";

 $register_car = basename(parse_url($url, PHP_URL_PATH));

 echo $register_car; // will echo "register-car"

?>

Upvotes: 2

Related Questions