Php get value of part of url

2019-09-18 06:59发布

I have a url (as below). I'd like to get the value of "2". How can I get that?

http://domain.com/site1/index.php/page/2

标签: php url
2条回答
神经病院院长
2楼-- · 2019-09-18 07:33

What you're looking for is a combination of pathinfo and parseurl:

pathinfo(parseurl($url)['path'])['filename'];

pathinfo will break the path into well-defined parts, of which filename is that last part you're looking for (2). If you're looking instaed for the absolute location in the path, you may want to split the path on / and simply get the value at index 3.

We can test this like so:

<?php
$url = "http://domain.com/site1/index.php/page/2";
$value=pathinfo(parse_url($url)['path'])['filename'];
echo $value."\n";

And then on the command line:

$ php url.php 
2
查看更多
祖国的老花朵
3楼-- · 2019-09-18 07:45

I use nathaniel fords example but if you run into a problem where files are named '2.html' some servers will load those even though you have '2'.

You can also do this.

home.php?page=2 as the web address

home.php
<?php
    // check to see if $page is set
    $page = $POST[page];
    $page = preg_replace('/\D/', '', $page);
    if(!isset($page)){
       query page two stuff or what you need.
    }
?>
查看更多
登录 后发表回答