如何在 php 中查找、增加和替换? [英] How can I find, increment and replace in php?
问题描述
我有 \d+_\d+
形式的字符串,我想在第二个数字上加 1.由于我的解释非常清楚,让我举几个例子:
I have strings in the form \d+_\d+
and I want to add 1 to the second number. Since my explanation is so very clear, let me give you a few examples:
- 1234567_2 应该变成 1234567_3
- 1234_10 应该变成 1234_11
这是我的第一次尝试:
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)$2)+1, $old);
这会导致语法错误:
解析错误:语法错误,意外T_LNUMBER,期待 T_VARIABLE 或 '$'在 [...] 第 201 行
Parse error: syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or '$' in [...] on line 201
这是我的第二次尝试
$new = preg_replace("/(\d+)_(\d+)/", "$1_".("$2"+1), $old);
这将 $old = 1234567_2 转换为 $new = 1234567_1,这不是预期的效果
This transforms $old = 1234567_2 into $new = 1234567_1, which is not the desired effect
我的第三次尝试
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)"$2"+1), $old);
这产生了相同的结果.
通过这些尝试,我意识到我不明白新的 $1, $2, $3, .. 变量是如何真正起作用的,所以我真的不知道还能尝试什么,因为这些变量似乎不再退出 preg_replace 函数时存在...
By making these attempts, I realized I didn't understand how the new $1, $2, $3, .. variables really worked, and so I don't really know what else to try because it seems that these variables no longer exist upon exiting the preg_replace function...
有什么想法吗?
推荐答案
$new = preg_replace("/(\d+)_(\d+)/e", '"$1_" . ("$2" + 1)', $old);
$1
等术语实际上不是变量,它们是 preg_replace
将在替换文本中解释的字符串.所以没有办法使用直接基于文本的 preg_replace
来做到这一点.
The $1
etc terms are not actually variables, they are strings that preg_replace
will interpret in the replacement text. So there is no way to do this using straight text-based preg_replace
.
然而,正则表达式上的 /e
修饰符要求 preg_replace
将替换解释为代码,其中标记 $1
等实际上将被视为变量.您将代码作为字符串提供,preg_replace
将在适当的上下文中eval()
,使用其结果作为替换.
However, the /e
modifier on the regular expression asks preg_replace
to interpret the substitution as code, where the tokens $1
etc will actually be treated as variables. You supply the code as a string, and preg_replace
will eval()
it in the proper context, using its result as the replacement.
这篇关于如何在 php 中查找、增加和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!