How to increment numeric part of a string by one?

前端 未结 5 1581
耶瑟儿~
耶瑟儿~ 2020-12-11 01:39

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 incre

相关标签:
5条回答
  • 2020-12-11 01:41

    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
    
    0 讨论(0)
  • 2020-12-11 01:42

    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);
    }
    
    0 讨论(0)
  • 2020-12-11 01:44

    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

    0 讨论(0)
  • 2020-12-11 01:50

    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

    0 讨论(0)
  • 2020-12-11 01:50

    Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.

    >>> import re
    >>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
    >>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
    'AF-1235'
    
    0 讨论(0)
提交回复
热议问题