PHP 中字符串错误的递减运算符?
Decrement operator for strings bug in PHP?
increment/decrement 运算符函数中关于字符串的不一致 - 至少 - 我的 PHP 版本。这就是我的意思:
php > echo phpversion();
7.4.11
php > $test = 'abc12';
php > // increment works as expected
php > echo(++$test);
abc13
php > echo(++$test);
abc14
php > echo(++$test);
abc15
php > // but decrement fails
php > echo(--$test);
abc15
php > echo(--$test);
abc15
php > echo(--$test);
abc15
这是预期的行为吗?我应该提交错误报告还是什么?您知道解决方法吗?
编辑:归档 bug#80212
这是我最终选择的:
function decrement($str) {
$matches = preg_split('/(\d+)\z/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
@--$matches[1];
return implode($matches);
}
不会称它为优雅,但我会称它为功能性。
那是 documented behaviour(强调我的):
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.
increment/decrement 运算符函数中关于字符串的不一致 - 至少 - 我的 PHP 版本。这就是我的意思:
php > echo phpversion();
7.4.11
php > $test = 'abc12';
php > // increment works as expected
php > echo(++$test);
abc13
php > echo(++$test);
abc14
php > echo(++$test);
abc15
php > // but decrement fails
php > echo(--$test);
abc15
php > echo(--$test);
abc15
php > echo(--$test);
abc15
这是预期的行为吗?我应该提交错误报告还是什么?您知道解决方法吗?
编辑:归档 bug#80212
这是我最终选择的:
function decrement($str) {
$matches = preg_split('/(\d+)\z/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
@--$matches[1];
return implode($matches);
}
不会称它为优雅,但我会称它为功能性。
那是 documented behaviour(强调我的):
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.