gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:11:55 25 4
gpt4 key购买 nike

我在某个地方遇到了这个问题,我想知道如何使用 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 中垂直回显文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10784853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com