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?
Here's the solution for the PHP 5.3 (now when PHP supports lambdas)
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.
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.