简体   繁体   中英

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.

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!

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"

这个正则表达式应该也可以正常工作'/\\d+/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM