user2005646
user2005646

Reputation: 148

Get the filename (basename) value from $_SERVER['REQUEST_URI']

I have 2 links like this:
http://www.example.com/report/4fbb14
http://www.example.com/4fbb14

so $_SERVER['REQUEST_URI'] for them is like:

/report/4fbb14
/4fbb14

I just need to get 4fbb14

I have used

$r_url = str_replace("/","",$_SERVER['REQUEST_URI']);

But I need it to work for both links, is something like this acceptable?

$r_url = str_replace("(/ or report)","",$_SERVER['REQUEST_URI']);

Upvotes: 0

Views: 224

Answers (4)

ElefantPhace
ElefantPhace

Reputation: 3814

All the previous answers will work, except for php NoOb's, but if all the links will have the same format you can just do this:

$r_url = $_SERVER['REQUEST_URI'];
$r_url = str_replace("report","",$r_url);
$r_url = str_replace("/","",$r_url);
echo $r_url;

Upvotes: 2

Halim Qarroum
Halim Qarroum

Reputation: 14103

Using regular expressions

Looking for the value at the end of the string, coming just after a /.

if ( preg_match("/\/(\d+)$/", "http://www.site.com/report/4fbb14", $result) )
{
  $value = $result[1];
}

Using parse_url and a simple explode

$values = parse_url("http://www.site.com/report/4fbb14");
$parts_of_the_url = explode("/", $values['path']);
$result = end($parts_of_the_url);

Upvotes: 2

samayo
samayo

Reputation: 16495

if you want to get the 4fbb14

<?php 

$ex = explode('/', 'http://www.site.com/4fbb14');
echo $ex['3'];

Upvotes: 1

Marko D
Marko D

Reputation: 7576

Much simpler would be

$r_url = end(explode('/', $_SERVER['REQUEST_URI']));

That gives you whatever was after the last forward slash

Upvotes: 4

Related Questions