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

How to change integer value in preg_match PHP?

抱歉,如果我的问题很愚蠢,请有人帮我解决这个问题。

我有这样的字符串

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

这个$str_value是动态的,它会改变每一页。现在我需要将此字符串中的 9 替换为 10。添加整数 1 并替换

例如,如果 $str_value = "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/

基本上,正则表达式将捕获一个由斜杠括起来的纯整数,将其传递给回调函数,该回调函数将清除整数值,递增它,然后 return 将其替换为每个上的填充斜杠边.

感谢@Calimero 的回答!你比我快,但我也想 post 我的答案 ;-)

另一种可能性是使用组来获取整数。所以你不需要 trim $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;

我还建议另一种基于 explodeimplode 的方法,而不是做任何正则表达式的事情。在我看来,这更具可读性。

$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);