Incrementing a string by one in PHP

后端 未结 3 1378
臣服心动
臣服心动 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: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.

提交回复
热议问题