Jess McKenzie Jess McKenzie - 1 month ago 5
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?

Result:

$prev = http://domain.co.nz/pages/brand-02
$next = http://domain.co.nz/pages/brand-02


What I am wanting:

$prev = http://domain.co.nz/pages/brand-01 - Should not be able to go any lower then 01
$next = http://domain.co.nz/pages/brand-02


Code:

<?php

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

$pageSlug = $url;

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



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

$next=$pageSlug++;

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

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

?>

Answer

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:

<?php

$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>';
var_dump(get_defined_vars());
echo '</pre>';