如何更改preg_match PHP中的整数值?

如何更改preg_match PHP中的整数值?,php,preg-replace,preg-match,str-replace,Php,Preg Replace,Preg Match,Str Replace,对不起,如果我的问题很愚蠢,请有人帮我解决这个问题 我有一条像绳子一样的线 $str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/"; 此$str_值是动态的,它将更改每个页面。现在我需要将这个字符串中的9替换为10。添加整数1并替换 例如,如果$str\u值=”http://99.99.99.99/var/test/src/158-of-box.html/251/“ 那么输出应该是 http://99.99.99.99

对不起,如果我的问题很愚蠢,请有人帮我解决这个问题

我有一条像绳子一样的线

$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";
此$str_值是动态的,它将更改每个页面。现在我需要将这个字符串中的9替换为10。添加整数1并替换

例如,如果
$str\u值=”http://99.99.99.99/var/test/src/158-of-box.html/251/“

那么输出应该是

http://99.99.99.99/var/test/src/158-of-box.html/252/
我试图用preg_match替换,但我弄错了,请有人帮助我

$str = preg_replace('/[\/\d+\/]/', '10',$str_value );
$str = preg_replace('/[\/\d+\/]/', '[\/\d+\/]+1',$str_value );

您需要使用回调来增加值,但不能直接在正则表达式本身中进行,如下所示:

$lnk= "http://99.99.99.99/var/test/src/158-of-box.html/9/";
$lnk= preg_replace_callback("@/\\d+/@",function($matches){return "/".(trim($matches[0],"/")+1)."/";},$lnk); // http://99.99.99.99/var/test/src/158-of-box.html/10/

基本上,regexp将捕获一个由斜杠括起来的纯整数,并将其传递给回调函数,回调函数将清除整数值,增加整数值,然后返回它,并在每边用填充斜杠替换。

谢谢您的回答,@Calimero!你比我快,但我也想发布我的答案;-)

另一种可能是使用组获取整数。因此,您不需要修剪
$matches[0]
来删除斜杠

$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/9/";

$str = preg_replace_callback('/\/([\d+])\//', function($matches) {
    return '/'.($matches[1]+1).'/';
}, $str_value);

echo $str;

我还建议使用另一种基于
explode
intlode
的方法,而不是使用任何regexp。在我看来,这更具可读性

$str_value = "http://99.99.99.99/var/test/src/158-of-box.html/11/";

// explode the initial value by '/'
$explodedArray = explode('/', $str_value);

// get the position of the page number
$targetIndex = count($explodedArray) - 2; 

// increment the value
$explodedArray[$targetIndex]++; 

// implode back the original string
$new_str_value = implode('/', $explodedArray);

只是添加了一些解释来说明我对代码所做的更改。非常欢迎:)很好的尝试!老实说,您解决问题的方法是我的第一次尝试,当时我正在寻找一种方法,不仅删除trim()调用,而且删除之后的“用斜线填充”部分,这可能是一种更干净的解决方案。我在放弃之前玩了一会儿非捕获子模式。