6

need the last part of the url

http://example.com then the last part is nothing if it is http://example.com/i then last part is i if it is http://example.com/i/am/file.php then last part is file.php

not sure if I use regex or what

hakre
  • 193,403
  • 52
  • 435
  • 836
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221
  • how are you retrieving this url? via php? is it a variable already? – David Nguyen May 12 '11 at 20:34
  • possible duplicate of [Extract part from URL for a query string](http://stackoverflow.com/questions/3080530/extract-part-from-url-for-a-query-string) – outis Jun 14 '12 at 08:09

5 Answers5

19

This is a simple example:

 <?php
     $url = "http://example.com/i/am/file.php";
     $keys = parse_url($url); // parse the url
     $path = explode("/", $keys['path']); // splitting the path
     $last = end($path); // get the value of the last element 
 ?>

I hope this help you ;)

Vasil Dakov
  • 2,040
  • 2
  • 19
  • 38
5

There is a function called parse_url().

Marc B
  • 356,200
  • 43
  • 426
  • 500
Denis de Bernardy
  • 75,850
  • 13
  • 131
  • 154
3

For those of you using a CMS like WordPress or Magento that add a trailing slash, there is an easy addition to Vasil's solution:

<?php
 $url = "http://example.com/i/am/file.php";
 $keys = parse_url($url); // parse the url
 $path = explode("/", $keys['path']); // splitting the path
 $last = end($path); // get the value of the last element 
 $last = prev($path); // get the next to last element 
 ?> 

You can even just use a simple Request URI call like this:

    $request_path = $_SERVER['REQUEST_URI'];
    $path = explode("/", $request_path); // splitting the path
    $last = end($path);
    $last = prev($path);
2
$url = 'http://example.com/i/am/file.php';
$url = rtrim($url, '/');
preg_match('/([^\/]*)$/', $url, $match);
var_dump($match);

Test

powtac
  • 40,542
  • 28
  • 115
  • 170
0

Note that Vasil's example won't work if for some reason you have a trailing slash, as for instance some CMS systems will put at the end (Magento, I'm looking at you...)

Well, it'll work, but the end of the path is empty. Something to be aware of.