帮助编写代码,仅增加字符串 A10M10N80 最后部分中的数字(不是字母)。
字母数字字符串的长度不固定,可以是
A1M2N10
、A10M10N80
或A102M100N81
,数字总是在最后部分。
与字母数字字符串分开的数字将两个部分存储在变量中,以便稍后在增加数字后组合。
Ex.字母数字字符串
A1M2100N99
,将数字和字母与最后一部分分开,
`A1M2100N99 to A1M2100N and 99`
仅增加最后一个字母后面的数字(数字),然后将两部分合并。
尝试了下面的代码,但此代码正在提取所有数字并混合所有数字(结果如下)
目的是分隔数字,然后递增数字,仅将 A1M2100N 和 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";
请检查以下解决方案。检索到数字值后,您可以增加数字。
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;