Link to home
Start Free TrialLog in
Avatar of ray-solomon
ray-solomonFlag for United States of America

asked on

Incrementing alpha-numerical characters

What would be a good way to increment alpha-numerical characters? I could not think of a way to do this reliably or find a similar example somewhere. Like splitting up the alpha and numeric characters while incrementing the number and joining them together.

like this:
A1
A2
A3
A4...stay in A's until it reaches A999999

B1
B2
B3
B4...stay in B's until it reaches B999999


and so on until it gets to Z999999.

The goal is to put in a function, then I could give it a proper value and it would return the next incremented value.
ASKER CERTIFIED SOLUTION
Avatar of Zyloch
Zyloch
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ray-solomon

ASKER

Wow, thank you Zyloch. That is great!
I see there is already a solution, but since I took the time to write my own, I'll post it here anyway:

function nextValue($currentValue) {
      if ($currentValue = 'Z999999')
            return true;
      if (!preg_match('/^([A-Z])(\\d{1,6})$/s',$currentValue,$matches))
            return false;
      if ($matches[2]=='999999')
            return chr(ord($matches[1])+1) . '1';
      return $matches[1] . (string) ((integer) $matches[2] + 1);
}

returns true when it reaches 'Z999999', returns false when the input is invalid, and returns your desired string otherwise.
Thank you JamesCssl for your contribution.