Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php url explode

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

like image 906
user1616846 Avatar asked Feb 27 '13 17:02

user1616846


People also ask

What does explode() do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

What is parse URL?

URL parsing is a function of traffic management and load-balancing products that scan URLs to determine how to forward traffic across different links or into different servers. A URL includes a protocol identifier (http, for Web traffic) and a resource name, such as www.microsoft.com.

How can I get params in PHP?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.


1 Answers

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), '/');
like image 194
newfurniturey Avatar answered Sep 22 '22 03:09

newfurniturey