我想要增量数字的字符串格式。我的字符串以字母开头,包含少数前导0的数字。
$string = M001; //input
$alf= trim(str_replace(range(0,9),'',$string)); //removes number from string
$number = preg_replace('/[A-Za-z]+/', '', $string);// removes alphabets from the string
$number+=1;
$custom_inv_id = $alf.$number;
预期结果:
input M002 output M003
input A00003 output A00004
如果输入为M002,则使用上面的代码,我将输出为M3。我怎么能得到M003? 0的数量不固定。
答案 0 :(得分:1)
使用PHP @Test
public void testAlert() throws InterruptedException {
((JavascriptExecutor)driver).executeScript("document.getElementById('del7757_7540').click();");
Thread.sleep(5000); // I generally do not use/prefer thread.sleep
System.out.println(driver.switchTo().alert().getText());
driver.switchTo().alert().accept();
}
或preg_match
并尝试以下代码: -
str_replace
答案 1 :(得分:1)
<?php
$tests = ['M0', 'M1', 'M001', 'M9', 'M09', 'M010',
'M2M0', 'M2M1', 'M2M001', 'M2M9', 'M2M09', 'M2M010',
'M2M', 'MM', '9M'];
foreach ($tests as $string) {
if (preg_match('/([\w\W]+)([0-9]+)$/', $string, $matches)) {
$output_string = $matches[1] . ($matches[2] + 1);
echo '<p>' . $string . ' => ' . $output_string . '</p>';
} else {
echo '<p>' . $string . ' (nothing to increment)</p>';
}
}
答案 2 :(得分:0)
您可以使用sprintf
和preg_match
函数来获得预期结果。
preg_match
拆分为分隔值,以便与sprintf
http://php.net/manual/en/function.sprintf.php http://php.net/manual/en/function.preg-match.php
function increase($string, $amount = 1) {
$valid = preg_match("#^(.)(0+)?(\d+)$#s", $string, $matches);
if($valid) {
list($match, $char, $zero, $integer) = $matches;
$integer += $amount;
return sprintf("%s%'.0" . (strlen($zero)+1) . "d", $char, $integer);
}
return null;
}
echo increase("M00001"); // M00002
echo increase("A001", 5); // A006
答案 3 :(得分:0)
$a = 'm002';
$pattern = '#(?P<word>[A-Za-z0]+)(?P<digtt>[1-9]+)#';
preg_match($pattern, $a, $matches);
$final = $matches['word'].(string)($matches['digtt']+1);
echo $final;
答案 4 :(得分:0)
我希望这可以帮到你。我做了一些动态使M%也动态
<?php
$vl = "A00004";
$number = substr($vl ,1);
$num= substr_count($vl,0);
$num++;
$number++;
$string = "M%'. 0".$num."d";
echo sprintf($string, $number);
?>
我得到了这个结果
M00005
答案 5 :(得分:0)
当复制前导0时,我会这样做。如果前导字符也是小写的话,它可以工作。它也是一种非正则表达式和非阵列方式。
$str = "M0099";
$num = ltrim($str, "a..zA..Z0");
$new = str_replace($num, $num + 1, $str);
<强>输出:强>
echo $new; // string(6) "M00100"