How can I find, increment and replace in php?

北城余情 提交于 2019-12-02 01:11:01
$new = preg_replace("/(\d+)_(\d+)/e", '"$1_" . ("$2" + 1)', $old);

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.

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.

Here's the solution for the PHP 5.3 (now when PHP supports lambdas)

$new = preg_replace_callback("/(\d+_)(\d+)", function($matches)
{
    return $matches[1] . (1 + $matches[2]);
}
, $new);

Use explode (step-by-step):

$string = "123456_2";

echo $string;

$parts = explode("_", $string);

$lastpart = (int)$parts[1];

$lastpart++;

$newstring = $parts[0] . "_" . (string)$lastpart;

echo $newstring;

This separates the string on the "_" character and converts the second part to an integer. After incrementing the integer, the string is recreated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!