php url explode

后端 未结 3 1179
逝去的感伤
逝去的感伤 2020-12-20 23:53

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 an

3条回答
  •  别那么骄傲
    2020-12-21 00:19

    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), '/');
    

提交回复
热议问题