如何在 php 中查找、增加和替换?
我有 \d+_\d+
形式的字符串,我想在第二个数字上加 1。由于我的解释非常清楚,让我举几个例子:
- 1234567_2 应该变成 1234567_3
- 1234_10 应该变成 1234_11
这是我的第一次尝试:
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)$2)+1, $old);
这会导致语法错误:
解析错误:语法错误,意外 T_LNUMBER,需要 T_VARIABLE 或 '$' 在 [...] 第 201 行
这是我的第二次尝试
$new = preg_replace("/(\d+)_(\d+)/", "$1_".("$2"+1), $old);
这将 $old = 1234567_2 转换为 $new = 1234567_1,这不是所需的效果
我的第三次尝试
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)"$2"+1), $old);
这产生了相同的结果。
通过这些尝试,我意识到我不明白新的 $1、$2、$3、.. 变量是如何真正工作的,所以我真的不知道还能尝试什么,因为这些变量在退出时似乎不再存在preg_replace 函数...
有什么想法吗?
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 should become 1234567_3
- 1234_10 should become 1234_11
Here is my first attempt:
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)$2)+1, $old);
This results in a syntax error:
Parse error: syntax error, unexpected
T_LNUMBER, expecting T_VARIABLE or '$'
in [...] on line 201
Here is my second attempt
$new = preg_replace("/(\d+)_(\d+)/", "$1_".("$2"+1), $old);
This transforms $old = 1234567_2 into $new = 1234567_1, which is not the desired effect
My third attempt
$new = preg_replace("/(\d+)_(\d+)/", "$1_".((int)"$2"+1), $old);
This yeilds the same result.
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...
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$1
等术语实际上并不是变量,它们是preg_replace
将在替换文本中解释的字符串。因此,无法使用直接基于文本的preg_replace
来做到这一点。但是,正则表达式上的
/e
修饰符要求preg_replace
将替换解释为代码,其中标记$1
等实际上将被视为变量。您以字符串形式提供代码,preg_replace
将在适当的上下文中eval()
它,并使用其结果作为替换。The
$1
etc terms are not actually variables, they are strings thatpreg_replace
will interpret in the replacement text. So there is no way to do this using straight text-basedpreg_replace
.However, the
/e
modifier on the regular expression askspreg_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, andpreg_replace
willeval()
it in the proper context, using its result as the replacement.这是 PHP 5.3 的解决方案(现在 PHP 支持 lambda)
Here's the solution for the PHP 5.3 (now when PHP supports lambdas)
使用
explode
(逐步):这会分隔“_”字符上的字符串,并将第二部分转换为整数。递增整数后,将重新创建字符串。
Use
explode
(step-by-step):This separates the string on the "_" character and converts the second part to an integer. After incrementing the integer, the string is recreated.