0

We have a link like http://stackoverflow.com/questions/9281910/h1-and-semantic-html5

How do I get the part, which is before the last and after last but one /?

In this example we would get h1-and-semantic-html5

More examples:

From the link http://dribbble.com/highlights/2012/ we get 2012

From http://www.apple.com/iphone/ we get iphone

animuson
  • 53,861
  • 28
  • 137
  • 147
Jasper
  • 5,090
  • 11
  • 34
  • 41
  • possible duplicate of [Get Last Part of URL PHP](http://stackoverflow.com/questions/7395049/get-last-part-of-url-php) – Gordon Feb 14 '12 at 18:58

2 Answers2

10

basename should provide what you're looking for:

php > echo basename("http://stackoverflow.com/questions/9281910/h1-and-semantic-html5");
h1-and-semantic-html5

php > echo basename("http://dribbble.com/highlights/2012/");
2012

php > echo basename("http://www.apple.com/iphone/");
iphone

Read more about it in the documentation.

thetaiko
  • 7,816
  • 2
  • 33
  • 49
  • You might want to use [`parse_url()`](http://php.net/parse_url) to get the *path* part of the URL, then use `basename()` on that. – salathe Feb 14 '12 at 19:02
1
$fin = preg_replace('#.*/([^/]+)/?$#', '$1', $whole);

Grab the last portion of non-forward slash characters (potentially followed by a forward slash)

Shad
  • 15,134
  • 2
  • 22
  • 34