6

I am wanting to grab my product from my url. For example:

http://www.website.com/product-category/iphone

I am wanting to grab the iphone and that is fine with my code but I have a dropdown to sort products and which clicked will change the url and add a query like:

http://www.website.com/product-category/iphone?orderby=popularity
http://www.website.com/product-category/iphone?orderby=new
http://www.website.com/product-category/iphone?orderby=price
http://www.website.com/product-category/iphone?orderby=price-desc

My current code is

$r = $_SERVER['REQUEST_URI']; 
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array()); 

$endofurl = $r[1];
echo $endofurl;

How is it possible to grab the iphone section all the time.

Cheers

1
  • Will the product name always follow /product-category/ ? Commented Feb 27, 2013 at 17:12

3 Answers 3

7

You can use PHP's parse_url() function to split the URL for you and then access the path parameter and get the end of it:

$r = parse_url($url);
$endofurl = substr($r['path'], strrpos($r['path'], '/'));

This will parse the URL and then take a "sub-string" of the URL starting from the last-found / in the path.

You can alternatively use explode('/') as you're currently doing on the path:

$path = explode($r['path']);
$endofurl = $path[count($path) - 1];

UPDATE (using strrchr(), pointed out by @x4rf41):
A shorter method of obtaining the end of the string, opposed to substr() + strrpos() is to use strrchr():

$endofurl = strrchr($r['path'], '/');

If you take advantage of parse_url()'s option parameters, you can also get just the path by using PHP_URL_PATH like $r = parse_url($url, PHP_URL_PATH);

Or, the shortest method:

$endofurl = strrchr(parse_url($url, PHP_URL_PATH), '/');
Sign up to request clarification or add additional context in comments.

1 Comment

even shorter would be $endofurl = strrchr(parse_url($url, PHP_URL_PATH),'/');
5

If you want to retrieve the last element of the array, you can use the end function. The rest of your code seems to be working.

$endofurl = end($r);

You could also leverage parse_url and strrchr functions to make it more concise:

$endofurl = strrchr(parse_url($url, PHP_URL_PATH), '/');

Comments

4

Just figured it out.This now works with

$r = $_SERVER['REQUEST_URI']; 
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array()); 
$r = preg_replace('/\?.*/', '', $r);

$endofurl = $r[1];
echo $endofurl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.