Jess McKenzie Jess McKenzie - 1 year ago 49
PHP Question

++ working in a strange way on URL

I am trying to produce the following urls however with the code below I am getting this why?


$prev =
$next =

What I am wanting:

$prev = - Should not be able to go any lower then 01
$next =



$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$pageSlug = $url;

echo 'prev = ' .$prev. '<br/>';

echo 'next' . '<br/>' . '<br/>';


echo 'next = ' .$next. '<br/>';

echo '<a href="' .$next.'" > Next</a>';


Answer Source

Since you're working with a string, you will need to extract the numerical part before incrementing or decrementing. Here is one way to do it:


$url = 'testing/.sad/05';

// get any numbers from end of string
$matches = array();
if (preg_match('#(\d+)$#', $url, $matches)) {
    // if we have a match
    $page = $matches[1];
    $prev = substr_replace($url, sprintf('%02d', $page - 1), -strlen($page));
    $next = substr_replace($url, sprintf('%02d', $page + 1), -strlen($page));
} else {
    $prev = $next = null;

echo '<pre>';
echo '</pre>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download