なんか、気付いたら書いていたのだけれど、書き終った時に、なぜ書いていたのか思い出せず、しかも、現在の作業とまるで関係ないコードだったため、お蔵入りになることが確定した。供養のために投稿しておく。
<?php
$string = '私は宇宙人ですが地球人でもあります。私は宇宙人でした。私は宇宙人だったような気もします。';
echo "<< original >>\n";
echo $string . "\n";
echo "<< converted >>\n";
$result = convertVerticalLayout($string);
for ($i = 0; $i < count($result); $i++) {
for ($j = 0; $j < count($result[$i]); $j++) {
echo $result[$i][$j];
}
echo "\n";
}
function convertVerticalLayout ($string) {
$lines = explode ('。', $string);
unset($lines[count($lines) - 1]);
$maxLength = 0;
$lineCount = count($lines);
for ($i = 0; $i < $lineCount; $i++) {
$line = $lines[$i];
$lines[$i] = array();
$j = 0;
for (; $j < mb_strlen($line, 'UTF8'); $j++) {
$lines[$i][$j] = mb_substr($line, $j, 1, 'UTF8');
}
$lines[$i][$j] = '。';
if ($maxLength < count($lines[$i])) {
$maxLength = count($lines[$i]);
}
}
$result = array();
for ($j = 0; $j < $maxLength; $j++) {
for ($i = 0; $i < $lineCount; $i++) {
$result[$j][$lineCount - 1 - $i] = isset($lines[$i][$j]) ? $lines[$i][$j] : ' ';
}
}
return $result;
}