Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment numeric part of a string by one?

Tags:

string

regex

php

I have a string formed up by numbers and sometimes by letters.

Example AF-1234 or 345ww.

I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?

like image 861
tampe125 Avatar asked Nov 30 '10 11:11

tampe125


4 Answers

You can use preg_replace_callback as:

function inc($matches) {
    return ++$matches[1];
}

$input = preg_replace_callback("|(\d+)|", "inc", $input);

Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.

Ideone link

Alternatively this can be done using preg_replace() with the e modifier as:

 $input = preg_replace("|(\d+)|e", "$1+1", $input);

Ideone link

like image 113
codaddict Avatar answered Oct 16 '22 15:10

codaddict


If the string ends with numeric characters it is this simple...

$str = 'AF-1234';
echo $str++; //AF-1235

That works the same way with '345ww' though the result may not be what you expect.

$str = '345ww';
echo $str++; //345wx

@tampe125

This example is probably the best method for your needs if incrementing string that end with numbers.

$str = 'XXX-342';
echo $str++; //XXX-343
like image 33
Mavelo Avatar answered Oct 16 '22 15:10

Mavelo


Here is an example that worked for me by doing a pre increment on the value

$admNo = HF0001;
$newAdmNo = ++$admNo;

The above code will output HF0002

like image 7
DevsMind Avatar answered Oct 16 '22 16:10

DevsMind


If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.

For example if you have a number INV00-10-99 which should increment to INV00-11-00.

I ended up with the following:

for ($i = strlen($string) - 1; $i >= 0; $i--) {
  if (is_numeric($string[$i])) {
    $most_significant_number = $i;
    if ($string[$i] < 9) {
      $string[$i] = $string[$i] + 1;
      break;
    }
    // The number was a 9, set it to zero and continue.
    $string[$i] = 0;
  }
}

// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
  $string = substr_replace($string, '1', $most_significant_number, 0);
}
like image 2
pfrenssen Avatar answered Oct 16 '22 15:10

pfrenssen