0

我有一个从网站上得到的字符串。

字符串的一部分是“X2”,我想将 +1 添加到 2。

我得到的整个字符串是:

20120815_00_X2

我想要的是添加“X2”+1 直到“20120815_00_X13”

4

3 回答 3

1

你可以做 :

$string = '20120815_00_X2';

$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);

$incremented = $concat . ($num + 1);

echo $incremented;

有关 substr() 的更多信息,请参阅 =>文档

于 2012-08-15T14:40:58.377 回答
1

您想在字符串末尾找到数字并捕获它,测试最大值12并在这种情况下添加一个,因此您的模式看起来像:

/(\d+)$/    // get all digits at the end

和整个表达式:

$new = preg_replace('/(\d+)$/e', "($1 < 13) ? ($1 + 1) : $1", $original);

我使用了e修饰符,以便替换表达式将被评估为 php 代码。

请参阅CodePad上的工作示例。

于 2012-08-15T14:41:50.477 回答
1

该解决方案有效(无论 X 之后的数字是多少):

function myCustomAdd($string)
{

$original = $string;

$new = explode('_',$original);

$a = end($new);

$b = preg_replace("/[^0-9,.]/", "", $a);

$c = $b + 1;

$letters = preg_replace("/[^a-zA-Z,.]/", '', $a);

$d = $new[0].'_'.$new[1].'_'.$letters.$c;

return $d;

}

var_dump(myCustomAdd("20120815_00_X13"));

输出:

string(15) "20120815_00_X14"
于 2012-08-15T15:26:19.683 回答