Incrementing a string by one in PHP

后端 未结 3 1364
臣服心动
臣服心动 2020-12-22 12:40

I am struggling to find a way to increment a specific pattern required. For each new member, they are given a unique ID such as ABC000001. Each new members

相关标签:
3条回答
  • 2020-12-22 13:02

    As @axiac mentions this is probably not a good idea but it's pretty easy to manage.

    $memberid = 'ABC000001';
    list($mem_prefix,$mem_num) = sscanf($memberid,"%[A-Za-z]%[0-9]");
    echo $mem_prefix . str_pad($mem_num + 1,6,'0',STR_PAD_LEFT);
    

    Split your current member number into the alpha and numeric parts then put them back together bumping the number when you do it. I use this as a function and pass the previous ID and what I get back is the next ID in the sequence.

    0 讨论(0)
  • 2020-12-22 13:10

    You can extract only digits using regex to increment and using str_pad for create a prefix :

    $memberid = 'ABC000001';
    $num = preg_replace('/\D/', '',$memberid);
    echo sprintf('ABC%s', str_pad($num + 1, "6", "0", STR_PAD_LEFT));
    
    0 讨论(0)
  • 2020-12-22 13:13

    Possible answer without regex. Runs through each character and checks if it is a number or not. Then uses sprintf() to make sure leading 0s are still there.

    $str = "ABC000001";
    $number = "";
    $prefix = "";
    $strArray = str_split($str);
    foreach ($strArray as $char) {  
        if (is_numeric($char))  {
            $number .= $char;   
        } else {
            $prefix .= $char;   
        }
    }
    $length = strlen($number);
    
    $number = sprintf('%0' . $length . 'd', $number + 1);
    echo $prefix . $number;
    

    This works for this instance but would not work if the prefix had numbers in it.

    0 讨论(0)
提交回复
热议问题