2013-02-06 25 views
-1

我遇到的数据,如:如何通过PHP为数字添加+1?

$aa ="msg_1"; 

我想在字符串末尾添加+1做爆炸操作像下面后:

$nwMsg =explode("_",$aa); 
    $inMsg =number_format($nwMsg[1])+1; 
    $finStr =$nwMsg[0].'_'.$inMsg; 

这之后,我想形成再次重复相同的过程,但它增加到"10"之后,它不会增加...

+0

'$ inMsg = number_format($ nwMsg [1] + 1);' – BenM

+0

@BenM不工作 –

+0

定义不能工作,请。价值包含什么? – BenM

回答

1
function add_one($string) { 
    preg_match_all("/[a-zA-Z]+_\d+/", $string, $matches); 
    $elements = $matches[0]; 
    $last = $elements[count($elements)-1]; 
    $components = explode("_", $last); 
    $newnum = $components[1] + 1; 
    return $string . $components[0] . "_" . $newnum; 
} 
echo add_one("msg_1"); // prints "msg_1msg_2" 
echo add_one("msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9"); // prints "msg_1msg_2msg_3msg_4msg_5msg_6msg_7msg_8msg_9msg_10" 
+0

我想它像自动增量 –

+1

@SivaG你说它不工作,但现在你想自动增量。请确定你在问什么。 – Antony

+0

我希望它像“msg_1 ........ msg_10 .................. msg_100 ..... msg_1000 ......... ..“ –

3

您应该将+1放在number_format调用中,而不是后退它。

编辑:如果你只是想$nwMsg[1]被视为一个数字,只需加1到它将工作正常,因为+是一个数值运算符。

1
$nwMsg =explode("_",$aa); 
$inMsg =number_format($nwMsg[1] +1) ; 
$finStr =$nwMsg[0].'_'.$inMsg; 
1
$aa= "msg_1"; 
$new_string= explode("_", $aa); 
$new_aa= $new_string[0] ."10"; 
0

这是错误的

$inMsg =number_format($nwMsg[1])+1; 

这是它是如何做

$inMsg =number_format($nwMsg[1]+1); 
+0

相同的值显示伙计们.. 10 –

+0

@SivaG你究竟想要什么? –

+0

我希望它像“msg_1 ........ msg_10 .................. msg_100 ..... msg_1000 ......... ..“ –

0
$nwMsg =explode("_",$aa); 
$inMsg =$nwMsg[1] +1 ; 
$finStr =$nwMsg[0].'_'.$inMsg; 

您将获得使用number_format出结果。

+0

没有相同的价值,我越来越10 –

0

一件事,这可能会导致错误,你需要照顾 - 因为你要添加两个数字,首先要确保你转换$nwMsg[1]成数(整数或浮点数,这取决于):

$nwMsg =explode("_",$aa); 
    $inMsg =number_format((int)$nwMsg[1]+1); 
    $finStr =$nwMsg[0].'_'.$inMsg; 
0

如何不同的解决办法:

function add($matches) { 
    return ++$matches[0]; 
} 

$new = preg_replace_callback("(\d+)", "add", $aa);