将 +1 添加到从另一个站点获取的字符串


Add +1 to a string obtained from another site

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

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

我得到的整个字符串是:

20120815_00_X2

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

你可以

做:

$string = '20120815_00_X2';
$concat = substr($string, 0, -1);
$num = (integer) substr($string, -1);
$incremented = $concat . ($num + 1);
echo $incremented;

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

你想找到字符串末尾的数字并捕获它,测试最大值 12,如果是这种情况,添加一个,所以你的模式看起来像这样:

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

和整个表达式:

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

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

请参阅CodePad上的工作示例。

这个解决方案有效(不管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"