Need help with my pager PHP function now that I use mod-rewrite

倾然丶 夕夏残阳落幕 提交于 2019-12-01 12:26:21

问题


I am stuck now, here below is a snip from my paging code, this is the part the builds the URL for the paging links, it worked really great until now because now I am changing my whole site to use mod-rewrite so before a page would look like this

http://localhost/?p=mail.inbox&page=2

and now I want it to be like this..I already have the regex to do it but I need to change the way my paging builds links to the new URL's correctly

http://localhost/mail/inbox/page/2

here is the code that makes the OLD links, any help or ideas on how I can use for new links?

the catch is the way it works now is it can determine if other variables exist in the URL and if it see's them it will make sure it keeps them in the URL it makes when making new page links, for example is ?p=test&userid=2&color=green&page=3 it would make sure to keep all the extra stuff in the new url it makes and just increase or decrease the page number

$url_string = "?";
foreach ($_GET as $k => $v) {
    if ($k != "page") { // <-- the key you don't want, ie "page"
        if ($url_string != "?") {
            $url_string .= "&"; // Prepend ampersands nicely
        }
        $url_string .= $k . "=" . $v;
    }
}
$selfurl = $url_string . '&page=';
$page = $_GET['page'];
if ($page) {
    $start = ($page - 1) * $items_per_page;
}
else {
    $start = 0;
}
if ($page == 0) {
    $page = 1; //if no page var is given, default to 1.
}

回答1:


This will do the trick

$uri = $_SERVER['REQUEST_URI'];
$uri = preg_replace('#page/\d+/*#', '', $uri); // remove page from uri
$uri = preg_replace('#/$#', '', $uri); // remove trailing slash

$selfurl = $uri . '/page/';
$page = $_GET['page'];
if ($page) {
  $start = ($page - 1) * $items_per_page;
} else {
  $start = 0;
}
if ($page == 0) {
  $page = 1;
}

What the code is doing here is removing the /page/2 part from the uri if it exists and then you can modify the code as you want.
You mentioned that the code works if /page/1 part is not in the URI so removing that part if it exists should work too.



来源:https://stackoverflow.com/questions/1469067/need-help-with-my-pager-php-function-now-that-i-use-mod-rewrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!