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 ID should increment by one. So the second member’s ID would be ABC000002. I am using PHP and MySQL to keep track of each member but I have not been able to come up with a way to properly increment using the string format above.
What is the best way to approach this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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));
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0