在数学运算中使用 PHP preg_replace 匹配结果?
Using PHP preg_replace match result in a math operation?
我想在字符串中找到一个数字,将其加一,然后替换它。这些不起作用:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(""+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("")+1)."str", $original);
其中'str'是一个很好辨认的字符串,每一边都是数字(并且不包含数字)。
我知道我可以很容易地用不止一行代码来做到这一点,但看起来这应该是可能的。
仅使用 str_replace
你可以从字符串中获取数字,将其加一,然后用新数字替换旧数字:
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;
使用回调函数可以将匹配转换为数字并递增,例如:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);
我想在字符串中找到一个数字,将其加一,然后替换它。这些不起作用:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(""+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("")+1)."str", $original);
其中'str'是一个很好辨认的字符串,每一边都是数字(并且不包含数字)。
我知道我可以很容易地用不止一行代码来做到这一点,但看起来这应该是可能的。
仅使用 str_replace
你可以从字符串中获取数字,将其加一,然后用新数字替换旧数字:
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;
使用回调函数可以将匹配转换为数字并递增,例如:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);