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

在PHP中如何实现完整字符串的逐字符整体递增?

实现方案

PHP原生字符串++运算符的默认逻辑就是仅递增字符串的最后一个字符,同时支持字母进位规则(比如z递增后会变为aa),和你需要的逐字符全量递增逻辑不符,所以需要手动遍历每个字符单独处理。

以下是可直接使用的实现代码:

基础版本(按ASCII码直接+1,无循环)

function incrementEachChar(string $input): string
{
    $output = '';
    $length = strlen($input);
    for ($i = 0; $i < $length; $i++) {
        // 单个字符转ASCII码+1后转回字符
        $output .= chr(ord($input[$i]) + 1);
    }
    return $output;
}

// 测试调用
echo incrementEachChar('abc'); // 输出结果:bcd

增强版本(支持字母循环,z→a、Z→A)

如果需要处理字母边界场景,比如小写z递增后回到a,大写Z递增后回到A,可以使用如下适配版本:

function incrementEachCharWithCycle(string $input): string
{
    $output = '';
    $length = strlen($input);
    for ($i = 0; $i < $length; $i++) {
        $ascii = ord($input[$i]);
        if ($ascii >= ord('a') && $ascii < ord('z')) {
            $output .= chr($ascii + 1);
        } elseif ($ascii === ord('z')) {
            $output .= 'a';
        } elseif ($ascii >= ord('A') && $ascii < ord('Z')) {
            $output .= chr($ascii + 1);
        } elseif ($ascii === ord('Z')) {
            $output .= 'A';
        } else {
            // 非字母字符可自定义处理规则,这里保持默认+1逻辑
            $output .= chr($ascii + 1);
        }
    }
    return $output;
}

// 测试调用
echo incrementEachCharWithCycle('abz'); // 输出结果:bca
echo incrementEachCharWithCycle('YZ'); // 输出结果:ZA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:42:03