如何在PHP中垂直回显文本行?

flo*_*ree 13 php text

我在某个地方遇到了这个问题,我想知道如何使用PHP解决这个问题.鉴于此文本:

$str = '
PHP is a
widely-used

general-purpose
server side

scripting
language
';
Run Code Online (Sandbox Code Playgroud)

如何垂直回显文本,如下所示:

      g        
      e        
      n        
      e        
  w   r s      
  i   a e      
  d   l r   s  
P e   - v   c l
H l   p e   r a
P y   u r   i n
  -   r     p g
i u   p s   t u
s s   o i   i a
  e   s d   n g
a d   e e   g e
Run Code Online (Sandbox Code Playgroud)

我将选择更简单,更优雅的代码作为答案.

hak*_*kre 9

正如其他人已经证明的那样,array_map能够进行翻转,这基本上是您需要解决的主要问题.剩下的就是你如何安排代码.我认为你的版本非常好,因为它很容易理解.

如果您正在寻找更多其他极端,请小心处理:

$str = 'PHP is a
widely-used

general-purpose
server side

scripting
language';

$eol = "\n";
$turned = function($str) use ($eol) {
    $length = max(array_map('strlen', $lines = explode($eol, trim($str))));
    $each = function($a, $s) use ($length) {$a[] = str_split(sprintf("%' {$length}s", $s)); return $a;};
    return implode($eol, array_map(function($v) {return implode(' ', $v);}, call_user_func_array('array_map',
        array_reduce($lines, $each, array(NULL)))));
};

echo $turned($str), $eol;
Run Code Online (Sandbox Code Playgroud)

给你:

      g        
      e        
      n        
      e        
  w   r s      
  i   a e      
  d   l r   s  
P e   - v   c l
H l   p e   r a
P y   u r   i n
  -   r     p g
i u   p s   t u
s s   o i   i a
  e   s d   n g
a d   e e   g e
Run Code Online (Sandbox Code Playgroud)

这修复了另一个答案的输出,这是不正确的(现在已修复).

  • 这可能会赢得代码封锁竞赛. (2认同)

flo*_*ree 6

下面的代码将$str垂直打印.

$lines = preg_split("/\r\n/", trim($str));
$nl    = count($lines);
$len   = max(array_map('strlen', $lines));

foreach ($lines as $k => $line) {
  $lines[$k] = str_pad($line, $len, ' ', STR_PAD_LEFT);
}

for ($i = 0; $i < $len; $i++) {
  for ($j = 0; $j < $nl; $j++) {
    echo $lines[$j][$i].($j == $nl-1 ? "\n" : " ");
  }
}
Run Code Online (Sandbox Code Playgroud)