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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何在PHP中垂直回显文本行?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我在某个地方遇到这个问题,我想知道如何使用 PHP解决这个问题.给出这个文字
$str = '
PHP is a
widely-used

general-purpose
server side

scripting
language
';

如何垂直回显文字如下:

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

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

正如其他人已经展示的那样,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;

给你:

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

这会修复其他答案的输出,这是不正确的(现在已经修复).

脚本宝典总结

以上是脚本宝典为你收集整理的如何在PHP中垂直回显文本行?全部内容,希望文章能够帮你解决如何在PHP中垂直回显文本行?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。