Federico Giust
Federico Giust

Reputation: 1793

PHP Increment alphanumeric string

I working on a page where the user will see a table using datatables with a set of their data. They need to have the option to put their own numbering, could be just numbers or alphanumeric and the increment as well.

So it will have two inputs one for the starting number that could be anything they want like: 1, A01, 01, A01M and the list goes on. So the combinations could be endless.

And the list goes on, now the tricky bit is the increment. The user need to have the option to set the increment to be anything numeric and since it might have characters at the end which shouldn't change, the $n++ to increment alphanumeric string wont work here.

I've been googling around but the only ones I've found are for specific cases or to do the autoincrement using the ++.

Any help would be great.

Upvotes: 1

Views: 1401

Answers (3)

Faquarl
Faquarl

Reputation: 158

If you're not case-sensitive, you can use base_convert($string, 36,10). This will transform a string into a int (considering the string to be a number in base 36).

$var = base_convert('azz',36,10);
echo base_convert($var,10,36).PHP_EOL; $var+=1;
echo base_convert($var,10,36).PHP_EOL; $var+=1;
echo base_convert($var,10,36).PHP_EOL;

Will give you :

azz
b00
b01

But be aware that 6 caracters will already give you 36^6-1 ~ 2 Billion possibilities which is around the value of a simple interger!

Upvotes: 2

zvaehn
zvaehn

Reputation: 91

this regex should work as well '/\d+/'

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

In PHP you may use preg_replace_callback():

function increment($string)
{
   return preg_replace_callback('/^([^0-9]*)([0-9]+)([^0-9]*)$/', function($m)
   {
      return $m[1].str_pad($m[2]+1, strlen($m[2]), '0', STR_PAD_LEFT).$m[3];
   }, $string);
}

str_pad() is needed since we may have leading zeros, which are significant if speaking about strings. Some examples:

var_dump(increment('2000000000'));//string(10) "2000000001"
var_dump(increment('A040'));      //string(4) "A041"
var_dump(increment('A15MM'));     //string(5) "A16MM"
var_dump(increment('PY999LKD'));  //string(9) "PY1000LKD" 

Note, that this function will leave ambiguous cases untouched:

var_dump(increment('N008P91F'));  //string(8) "N008P91F"

Upvotes: 1

Related Questions