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

4

3 回答 3

6

您可以使用 PHP 的parse_url()函数为您拆分 URL,然后访问path参数并获取它的结尾:

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

/这将解析 URL,然后从路径中的 last-found 开始获取 URL 的“子字符串” 。

您也可以explode('/')像当前在路径上那样使用:

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

更新(使用strrchr(),@x4rf41 指出):
获取字符串结尾的一种更短的方法,与substr()+相反strrpos()是使用strrchr()

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

如果您利用parse_url()'s 选项参数,您还可以使用like $r = parse_url($url, PHP_URL_PATH);来获取路径。PHP_URL_PATH

或者,最短的方法:

$endofurl = strrchr(parse_url($url, PHP_URL_PATH), '/');
于 2013-02-27T17:13:24.807 回答
5

如果要检索数组的最后一个元素,可以使用end函数。您的其余代码似乎正在运行。

$endofurl = end($r);

您还可以利用parse_urlstrrchr函数使其更简洁:

$endofurl = strrchr(parse_url($url, PHP_URL_PATH), '/');
于 2013-02-27T17:11:57.033 回答
4

刚刚想通了。现在可以使用

$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;
于 2013-02-27T17:17:33.650 回答