Decrementing alphabetical values

前端 未结 3 1197
遥遥无期
遥遥无期 2020-11-28 16:18

I\'m trying to figure out how to shift a bunch of letter values in an array down one step. For example, my array contains values (\"d\", \"e\", \"f\", \"g\", \"h\") and I wa

3条回答
  •  攒了一身酷
    2020-11-28 17:01

    If you need to decrement Excel-like variables ('A', 'AA', ...), here's the function I came to. It doesn't work with special characters but is case insensitive. It returns null if you try to decrement 'a' or 'A'.

    function decrementLetter($char) {
         $len = strlen($char);
         // last character is A or a
         if(ord($char[$len - 1]) === 65 || ord($char[$len - 1]) === 97){ 
              if($len === 1){ // one character left
                   return null;
               }
               else{ // 'ABA'--;  => 'AAZ'; recursive call
                   $char = decrementLetter(substr($char, 0, -1)).'Z';
                }
         }
         else{
             $char[$len - 1] = chr(ord($char[$len - 1]) - 1);
         }
         return $char;
    }
    

提交回复
热议问题