在 PHP 中生成字母数字增量序列号
帮助编写代码以在最后一个字母之后增加数字(仅增加数字)。 像普通数字一样增加更多的数字,1s,10s,100s。
字母数字字符串
A1M2100N99
,始终为字母数字字符串,无需增加字母,仅增加最后一个字母之后的数字(数字),例如9增加到10,99增加到100,依此类推。
字符串始终是不固定长度的字母数字,可以是
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
请检查以下解决方案。检索到数字值后,您可以增加数字。
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
匹配 alpha 字符但忽略它们,然后拉出最后一个整数并递增它。
$string="A1M2100N99";
preg_match('/[a-z]\K\d+$/iu', $string, $number);
echo $number[0] + 1;