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,432
  • 9
  • 35
  • 59
  • 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
  • 20,559
  • 6
  • 64
  • 96
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
  • 312,895
  • 29
  • 395
  • 388
1
$url = rtrim($url, '/');
preg_match('/([^\/]*)$/', $url, $match);
var_dump($match);

Test

powtac
  • 40,542
  • 28
  • 115
  • 170
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,438
  • 1
  • 13
  • 25