Php url explodes

I want to take my product from my url. For instance:

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

I want to grab the iphone, and this is normal with my code, but I have a drop-down list for sorting the products, and by clicking the URL button, the URL will be changed and add a query, for example:

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

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

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

How can I grab the iphone section all the time.

Greetings

+5
source share
3 answers

You can use the PHP function parse_url()to split the url for you and then access the parameter pathand get its end

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

This will parse the URL and then take the “substring” of the URL, starting with the last found /in the path.

explode('/'), :

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

( strrchr(), @x4rf41):
, substr() + strrpos(), strrchr():

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

parse_url(), , PHP_URL_PATH like $ r = parse_url ($ url, PHP_URL_PATH);

:

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

, end. , , .

$endofurl = end($r);

parse_url strrchr, :

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

.

$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;
+2
source

All Articles