skip to Main Content

Help with code to increment only numbers (Not Alphabets) in last part of string A10M10N80.

alphanumeric string is not of fixed length, can be A1M2N10, A10M10N80, or A102M100N81, Always number will be in last part.

Separate number from Alphanumeric string store both parts in variable for combining later after incrementing the number.

Ex.alphanumeric string A1M2100N99, Separate numbers and alphabet from last part,

`A1M2100N99 to A1M2100N and 99`

Increment only numbers(digits) after last alphabet, then combine both parts.

Tried below code, but this code is extracting all numbers and mix all numbers (Result below)

Purpose is to separate numbers then increment digits only combine both parts A1M2100N and 99.

<?php
//$string="A1M01";
$string="A1M2100N99";
$chars = null ;
$nums = null ;
for ($index=0;$index<strlen($string);$index++) {
    if(preg_match('/[0-9]/',($string[$index])))
        $nums .= $string[$index];
    else
        $chars .= $string[$index];
}
    ++$nums;

echo "Letters: $chars n";
echo "Newber : $nums n";   

2

Answers


  1. Please check the below solution. After retrieving the number value, you can increment the number.

    function findNumberAfterLastChar($string) {
       // Find the position of the last character in the string
       $lastCharPos = strlen($string) - 1;
    
       // Loop backwards from the last character position until a non-numeric character is found
       $number = '';
      for ($i = $lastCharPos; $i >= 0; $i--) {
          if (is_numeric($string[$i])) {
            // If the character is numeric, prepend it to the number string
            $number = $string[$i] . $number;
          } else {
            // If a non-numeric character is encountered, break the loop
            break;
          }
       }
       return $number;
     }
    
    $string = "A1M2100N99";
    $numberAfterLastChar = findNumberAfterLastChar($string);
    echo "Number after last character: " . $numberAfterLastChar; // Output: 99
    
    Login or Signup to reply.
  2. Match the alpha char(s) but ignore them, then pull the last integer and increment it.

    $string="A1M2100N99";
    preg_match('/[a-z]Kd+$/iu', $string, $number);
    echo $number[0] + 1;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search