Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an alphanumeric string in PHP?

Tags:

string

php

There's a string, containing characters [a-zA-Z0-9]. This should be 26 * 2 + 10 = 62 possibilities in one character and 62^2 in two. What is the preferred way to increment a value of such a string, so that 'aA', becomes 'aB', etc.? Is there any built-in stuff in PHP, that can help?

I know you can increment a string, but that's only lowercase letters. Essentially, the result should go from 'a' to 'aa' in 61 increments.

like image 278
Fluffy Avatar asked Dec 02 '11 20:12

Fluffy


People also ask

How to generate alphanumeric auto increment id in PHP?

<? php $length = 4; $id = ''; for ($i=0;$i<$length;$i++){ $id . = rand(1, 9); } echo $id; ?>

How to increment letters like numbers in PHP?

This can be carried out using the simple increment (++) operator just like in numbers. The only point of difference being decrement (–) operator doesn't work the same in letters as it does in numbers.

Is alphanumeric in PHP?

A ctype_alnum() function in PHP used to check all characters of given string/text are alphanumeric or not. If all characters are alphanumeric then return TRUE, otherwise return FALSE. Parameters Used: $text : It is a mandatory parameter which specifies the string.


1 Answers

Try this function:

<?php
function increment(&$string){
    $last_char=substr($string,-1);
    $rest=substr($string, 0, -1);
    switch ($last_char) {
    case '':
        $next= 'a';
        break;
    case 'z':
        $next= 'A';
        break;
    case 'Z':
        $next= '0';
        break;
    case '9':
        increment($rest);
        $next= 'a';
        break;
    default:
        $next= ++$last_char;
    }
    $string=$rest.$next;
}

    //sample
    $string='a';
    for($i=1;$i<=128;$i++){
        echo $string."<br>";
        increment($string);
    }
    ?>
like image 100
phobia82 Avatar answered Oct 05 '22 01:10

phobia82