Una semplice funzione già pronta all’uso per alimentare un contatore alfanumerico
Immaginiamo di dover incrementare un contatore alfanumerico. In PHP è possibile incrementare valori numerici e alfanumerici, ma con questa funzione possiamo incrementare anche valori alfanumerici case sensitive.
Questa funzione in PHP consente, inserito un contatore alfanumerico case sensitive, di ottenere il successivo.
Esempi:
Input -> Output
17 -> 18
39 -> 3A
BZ -> Ba
La funzione è la seguente
function getNextAlphaNumeric($str, $step = 1) {
for ($x = 0; $x < strlen(strval($str)); $x++) {
$ord = ord( substr(strval($str), -1 - $x, 1) );
$nord = $ord + $step;
if ($nord > 57 && $ord <= 57) $nord += 7;
if ($nord > 90 && $ord <= 90) $nord += 6;
if ($nord <= 122) {
return substr_replace(strval($str), chr($nord), -1 - $x, 1);
} else {
$over = $nord - 122;
if ($over > 62) {
$step = floor( $over / 62 ) + 1;
$ord = 47 + ( $over % 62 );
} else {
$step = 1;
$ord = 47 + $over;
}
if ($ord > 57) $ord += 7;
if ($ord > 90) $ord += 6;
$str = substr_replace(strval($str), chr($ord), -1 - $x, 1);
}
}
return $str . '0';
}
Ovviamente riceve e richiede una stringa
$output= getNextAlphaNumeric('BZ');