字符串中以前导零开头的递增数字

时间:2019-03-06 11:29:02

标签: php

我有以下字符串“ S_000308”。

将数字加一的最佳方法是什么?例如:“ S_000309”“ S_000310”,.....

我尝试了各种方法,但问题似乎出在前导零上,这使操作变得困难。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

You're overcomplicating it. :) Perl had this magic, and many languages, including PHP, inherited it:

$x = "S_000308";
$x++;
echo $x;
// => S_000309

EDIT: Took a bit of searching for the right bit in the docs, but here there's an explanation, followed by some examples:

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

答案 1 :(得分:1)

You can extract the number with :

$number = intval(substr($string, 2));

And then formate the number with :

$string = "S_" . str_pad($number, 6, "0", STR_PAD_LEFT);

And in between you can do all the operation you want with $number, for example $number++; for incrementation.

答案 2 :(得分:0)

PHP can recognize the trailing numbers in strings and perform well for operator overloading.

$strNum = "Next year is 2019";

$strNum++;   // Next year is 2020