How to increment letters like numbers in PHP?

后端 未结 8 1362
孤城傲影
孤城傲影 2020-11-27 16:41

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 sing

相关标签:
8条回答
  • 2020-11-27 17:10

    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!

    0 讨论(0)
  • 2020-11-27 17:11
     <?php 
    $values[] = 'B';
    $values[] = 'A';
    $values[] = 'Z';
    foreach($values as $value ){
      if($value == 'Z'){ 
           $value = '-1';
        }
    $op = ++$value;
    echo $op;
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题