Question

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

Was it helpful?

Solution

$url = 'http://www.domain.co.uk/product/SportingGoods/Cookware/1/B000YEU9NA/Coleman-Family-Cookset';
$url = explode('/', $url);
$last = array_pop($url);
echo $last;

OTHER TIPS

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.

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.

$url = rtrim($url, '/');
preg_match('/([^\/]*)$/', $url, $match);
var_dump($match);

Test

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top