I ran into a problem the other day where I needed to increment an alphanumeric string. An alphanumeric string is a string consisting of both numerals and letters (0-9, a-z, A-Z). This combination of characters is base62, however, there is no base62 function in PHP to make this easy. There were a couple of solutions out there, but I didn’t really like any of them. So I decided to sit down and write out one that suited my needs. Here it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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 = 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; } |
I also created a GitHubGist for this snippet.