PHP 如何在字母数字字符串中最后一个字母之后递增数字

问题描述 投票:0回答:1

PHP:生成序列号,帮助使用代码在最后一个字母之后递增数字,像常规数字一样递增,添加更多数字,1、10、100。

字母数字字符串

A1M2100N99

字符串不固定长度,可以是

A1M2N10
A10M10N80
A102M100N81

尝试了下面的代码,但此代码正在提取所有数字并混合所有数字(结果如下)

所需结果

99
,然后将此数字增加到
100

目的是在最后一个字母之后增加数字(生成序列号)

<?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];
}
echo "Letters: $chars \n";
echo "Nums: $nums \n";

输出如下:(预期 99)

 1210099
php laravel
1个回答
0
投票

请检查以下解决方案

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
© www.soinside.com 2019 - 2024. All rights reserved.