Skip to content

Instantly share code, notes, and snippets.

@kikuchan
Created April 8, 2016 18:05
Show Gist options
  • Save kikuchan/ec3590df48396630bcb3faec707c3c8d to your computer and use it in GitHub Desktop.
Save kikuchan/ec3590df48396630bcb3faec707c3c8d to your computer and use it in GitHub Desktop.
Excelカラム名っぽいやつの相互変換
<?php
function fwd_conv($v) {
// 必要な桁数を求める のと同時に 該当桁数内での順番に変換する
for ($c = 1; $v >= pow(26, $c); $c++) $v -= pow(26, $c);
// 目標桁数のアルファベット26進表現に変換
$r = base_convert($v, 10, 26);
$r = str_pad($r, $c, '0', STR_PAD_LEFT);
$t = '0123456789abcdefghijklmnopqrstuvwxyz';
return strtr($r, $t, substr($t, 10));
}
function rev_conv($v) {
// アルファベット26進表現を10進に戻す
$t = '0123456789abcdefghijklmnopqrstuvwxyz';
$v = strtr(strtolower($v), substr($t, 10), $t);
$r = base_convert($v, 26, 10);
// 入力桁数未満の過ぎ去ったカウント分、ゲタを履かせる
for ($c = 1; $c < strlen($v); $c++) $r += pow(26, $c);
return $r;
}
$v = trim($argv[1]);
printf("%s\n", is_numeric($v) ? fwd_conv($v) : rev_conv($v));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment