2015-11-19 23 views
2

对不起,如果我的问题很愚蠢,请有人帮我解决这个问题。如何更改preg_match PHP中的整数值?

我有串状

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

这$ str_value是动态的,它会改变每一页。现在我需要在该字符串作为10.整数加1,以取代图9和替换

例如如果$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更换但即时得到错请pleasesone帮我

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

回答

1

您需要使用回调增加值,它不能直接在正则表达式中完成本身,像这样:

$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/ 

基本上,正则表达式将捕获由斜线包围的纯整数,其传递给回调函数将清除整数值,递增,然后返回它用于替换带衬垫斜线在每一边。

+0

谢谢@calimero :) –

+0

刚刚添加了一些解释来说明我对代码所做的更改。你最欢迎:) – Calimero

4

谢谢你的回答@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; 
+0

好的尝试!说实话,你解决问题的方式是我的第一枪,当时我正在寻找一种方法,不仅可以去除trim()调用,而且还可以去除之后的“填充斜杠”部分,这可能会更清洁解。在放弃之前,我玩弄了一段时间的不捕捉子模式。 – Calimero

1

我也建议基于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);