You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP技术问询:如何为字符串中所有数字加1且不重建字符串

PHP实现:为字符串中的数字加1天的方案

需求回顾

原字符串:"The delivery time will be 3-4 days. If you choose 'express' the delivery time will be 1-2 days. Pay within 30 days."
预期结果:"The delivery time will be 4-5 days. If you choose 'express' the delivery time will be 2-3 days. Pay within 31 days."

实现思路

嘿,我来给你分享个靠谱的实现思路:用PHP的preg_replace_callback()函数就搞定了。它能精准匹配字符串里的所有数字,然后通过回调函数给每个匹配到的数字自动加1,全程基于原字符串做替换,完全不用手动重新拼接新字符串。

代码实现

<?php
$originalStr = "The delivery time will be 3-4 days. If you choose 'express' the delivery time will be 1-2 days. Pay within 30 days.";

// 匹配所有数字并逐个加1
$processedStr = preg_replace_callback(
    '/\d+/',
    function($matches) {
        // 把匹配到的数字转成整数加1后返回
        return (int)$matches[0] + 1;
    },
    $originalStr
);

// 输出处理后的结果
echo $processedStr;
?>

代码说明

  • \d+是正则表达式,用来匹配字符串中所有连续的数字(像3、4、1、2、30这类都会被精准命中)
  • 回调函数负责把匹配到的数字字符串转成整数,执行加1操作后再转回字符串返回
  • 整个过程是对原字符串的替换处理,完全符合你“不重新创建字符串”的要求

运行这段代码,就能直接得到你想要的预期结果啦~

内容的提问来源于stack exchange,提问作者Werner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:31:10