Jump to content

[SOLVED] addition issue on alphanumeric value


Walker33

Recommended Posts

I have a three digit alphanumeric value that I'm adding 1 to, for instance S07.  My code works fine for all situations except 09, 19, 29, etc.  For instance, S09 becomes S010 instead of what I want, which is S10, S19 becomes S110 instead of S20, etc.  Not sure what to do, and I also need to avoid S11 becoming S22, S22 becoming S33, etc.

 

<?php
//$res is S09 in this case
$number = (int) $res[2];
$new_number = $number+1;
$reso = substr_replace($res, $new_number, 2);
//$reso becomes S010 instead of S10

?>

 

Really appreciate any help!

Link to comment
Share on other sites

do you mean something like this

<?php
$res = "S19";
//$res = substr($res,0,1).(substr($res,1)+1);
$res = substr($res,0,1).sprintf('%02s', (substr($res,1)+1)); //Updated
echo $res;
?>

that works with 1 letter then 2 numbers

 

 

if you need something my complex ie unknown number of letter followed by 1 or more numbers then this maybe better

<?php
$res = "Something19";
if (preg_match('/([a-z]*)(\d+)/i', $res,$match)) {
//$res = $match[1].($match[2]+1);
$res = $match[1].sprintf('%02s', $match[2]+1)); //Updated
}
echo $res;
?>

 

this will work with any letters follow by 1 or 2 numbers

 

EDIT: oops missed something

just updated to so 01 would become 02 instead of just 2

Link to comment
Share on other sites

It's always just one letter followed by two numbers.  The first code you gave me does work for the 09, 29, etc., issue.  However, it also changes S07 into S8 instead of what I need, which would be S08.  I always need it to be three digits.  Further thoughts?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.