Skip to content

Instantly share code, notes, and snippets.

@josevh
Forked from lewayotte/alphanumeric_increment.php
Last active May 9, 2018 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josevh/6472a54d452f3fd48ef5ef03712ae357 to your computer and use it in GitHub Desktop.
Save josevh/6472a54d452f3fd48ef5ef03712ae357 to your computer and use it in GitHub Desktop.
Incrementing alphanumeric strings in PHP
function alphanumeric_increment( $string, $position=false ) {
if ( false === $position ) {
$position = strlen( $string ) - 1;
}
$increment_str = substr( $string, $position, 1 );
switch ( $increment_str ) {
case '9':
$string = substr_replace( $string, 'a', $position, 1 );
break;
case 'z':
$string = substr_replace( $string, 'A', $position, 1 );
break;
case 'Z':
if ( 0 === $position ) {
$string = substr_replace( $string, '0', $position, 1 );
$string .= '0';
} else {
$inc_position = $position - 1;
$string = alphanumeric_increment( $string, $inc_position );
$string = substr_replace( $string, '0', $position, 1 );
}
break;
default:
$increment_str++;
$string = substr_replace( $string, $increment_str, $position, 1 );
break;
}
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment