简体   繁体   English

PHP增量字母数字字符串

[英]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. 因此,这将有两个输入一个起始编号,可能是他们想喜欢什么: 1A0101A01M和这样的例子不胜枚举。 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. 用户需要选择将增量设置为任何数字,因为它可能在末尾有不应更改的字符, $n++增加字母数字字符串在这里不起作用。

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) . 如果您不区分大小写,则可以使用base_convert($string, 36,10) This will transform a string into a int (considering the string to be a number in base 36). 这会将字符串转换为int(将字符串视为基数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! 但请注意,6个字符已经为您提供36 ^ 6-1~2亿个可能性,这是一个简单的整数的价值!

In PHP you may use preg_replace_callback() : 在PHP中,您可以使用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. str_pad()是必需的,因为我们可能有前导零,如果谈到字符串,这是很重要的。 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+/'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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