How to increment numeric part of a string by one?

前端 未结 5 1604
耶瑟儿~
耶瑟儿~ 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: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);
    }
    

提交回复
热议问题