0

Possible Duplicate:
extract last part of a url

I have a url like this:

http://www.domain.co.uk/product/SportingGoods/Cookware/1/B000YEU9NA/Coleman-Family-Cookset

I want extract just the product name off the end "Coleman-Family-Cookset"

When I use parse_url and print_r I end up with the following:

Array (
    [scheme] => http
    [host] => www.domain.co.uk
    [path] => /product/SportingGoods/Cookware/1/B000YEU9NA/Coleman-Family-Cookset
) 

How do I then trim "Coleman-Family-Cookset" off the end?

Thanks in advance

Community
  • 1
  • 1
Ben Paton
  • 1,424
  • 8
  • 34
  • 56
  • 1
    http://stackoverflow.com/questions/5983943/extract-last-part-of-a-url – Haim Evgi Feb 19 '12 at 12:22
  • Ok I've done it like this: ''$lastPart = parse_url($url); $lastPart = $lastPart[path]; $lastPart = explode("/", $lastPart); echo $lastPart[6];'' any improvement? – Ben Paton Feb 19 '12 at 12:24

4 Answers4

7

All the answers above works but all use unnecessary arrays and regular expressions, you need a position of last / which you can get with strrpos() and than you can extract string with substr():

substr( $url, 0, strrpos( $url, '/'));

You'll maybe have to add +/- 1 after strrpos()

This is much more effective solution than using preg_* or explode, all work though.

Vyktor
  • 19,854
  • 5
  • 58
  • 94
1
$url = 'http://www.domain.co.uk/product/SportingGoods/Cookware/1/B000YEU9NA/Coleman-Family-Cookset';
$url = explode('/', $url);
$last = array_pop($url);
echo $last;
adeneo
  • 303,455
  • 27
  • 380
  • 377
1
$url = rtrim($url, '/');
preg_match('/([^\/]*)$/', $url, $match);
var_dump($match);

Test

powtac
  • 39,317
  • 26
  • 112
  • 166
1

You have the path variable(from the array as shown above). Use the following:

$tobestripped=$<the array name>['path']; //<<-the entire path that is
$exploded=explode("/", $tobestripped);
$lastpart=array_pop($exploded);

Hope this helps.

Akshaya Shanbhogue
  • 1,409
  • 1
  • 12
  • 24