5

Possible Duplicate:
Extracting the last segment on an URI

I want to get the last parameter of the url for eg.

http://www.youtube.com/embed/ADU0QnQ4eDs

I have a full url like above and i want to get only last parameter with the PHP which is ADU0QnQ4eDs

Please help

Community
  • 1
  • 1
ManpreetSandhu
  • 2,115
  • 5
  • 20
  • 17
  • 5
    `echo basename("http://www.youtube.com/embed/ADU0QnQ4eDs");` – Andreas Wong Jun 29 '12 at 07:48
  • 1
    [please use the search function before asking duplicates. How to get the last segment in the url path has been asked and answered a dozen times before](http://stackoverflow.com/search?q=get+last+segment+of+url+[php]) – Gordon Jun 29 '12 at 08:00
  • 1
    Those "duplicates" are full of the end/explode "help" offered here. – salathe Jun 29 '12 at 08:15

3 Answers3

15

Something like this?

echo end(explode("/", $url));

This will throw an error if strict error reporting is enabled. To avoid this, split them up like this:

$parts = explode("/", $url);
echo end($parts);
Repox
  • 15,015
  • 8
  • 54
  • 79
9

There are functions for that.

$url      = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);

// $basename is "ADU0QnQ4eDs"

See http://php.net/parse_url and http://php.net/pathinfo.

salathe
  • 51,324
  • 12
  • 104
  • 132
1

You have a pattern here that can be easily scanned:

$interestedIn = sscanf($url, 'http://www.youtube.com/embed/%s');

Don't make your live more complicated than it needs to be. Technically substr would work, too, but this one adds more context.

hakre
  • 193,403
  • 52
  • 435
  • 836