How to increment letters like numbers in PHP?

2020-01-24 21:09发布

I would like to write a function that takes in 3 characters and increments it and returns the newly incremented characters as a string.

I know how to increase a single letter to the next one but how would I know when to increase the second letters and then stop and then increase the first letter again to have a sequential increase?

So if AAA is passed, return AAB. If AAZ is passed return ABA (hard part).

I would appreciate help with the logic and what php functions will be useful to use.

Even better, has some done this already or there is a class available to do this??

Thanks all for any help

标签: php
8条回答
闹够了就滚
2楼-- · 2020-01-24 21:53

I have these methods in c# that you could probably convert to php and modify to suit your needs, I'm not sure Hexavigesimal is the exact name for these though...

#region Hexavigesimal (Excel Column Name to Number)
public static int FromHexavigesimal(this string s)
{
    int i = 0;
    s = s.Reverse();
    for (int p = s.Length - 1; p >= 0; p--)
    {
        char c = s[p];
        i += c.toInt() * (int)Math.Pow(26, p);
    }

    return i;
}

public static string ToHexavigesimal(this int i)
{
    StringBuilder s = new StringBuilder();

    while (i > 26)
    {
        int r = i % 26;
        if (r == 0)
        {
            i -= 26;
            s.Insert(0, 'Z');
        }
        else
        {
            s.Insert(0, r.toChar());
        }

        i = i / 26;
    }

    return s.Insert(0, i.toChar()).ToString();
}

public static string Increment(this string s, int offset)
{
    return (s.FromHexavigesimal() + offset).ToHexavigesimal();
}

private static char toChar(this int i)
{
    return (char)(i + 64);
}

private static int toInt(this char c)
{
    return (int)c - 64;
}
#endregion

EDIT

I see by the other answers that in PHP you can use ++ instead, nice!

查看更多
forever°为你锁心
3楼-- · 2020-01-24 21:54

You are looking at a number representation problem. This is base24 (or however many numbers your alphabet has). Lets call the base b.

Assign a number to each letter in alphabet (A=1, B=2, C=3).

Next, figure out your input "number": The representation "ABC" means A*b^2 + B*b^1 + C*b^0 Use this formula to find the number (int). Increment it.

Next, convert it back to your number system: Divide by b^2 to get third digit, the remainder (modulo) by b^1 for second digit, the remainder (modulo) by `b^0^ for last digit.

This might help: How to convert from base10 to any other base.

查看更多
登录 后发表回答