gpt4 book ai didi

php - 在变量中添加空格

转载 作者:行者123 更新时间:2023-11-27 23:18:38 26 4
gpt4 key购买 nike

晚上好

我在创建变量时添加了空格。这正是我所需要的,但现在我需要将文本集中在空格之间:

这是 PHP 代码:

$psn = "ABCDEFGH";
$psnSize = strlen($psn);

while($psnSize <= 20)
{
$psn = $psn."&nbsp";
$psnSize++;
}

最大大小为 20 个字符,我需要所有 psn 的大小相同(20 个字符)

我得到了结果,但空格被添加到文本的末尾,现在我想在文本之间分配空格以使其集中。

非常感谢。

最佳答案

您可以使用所有 native 函数来实现此目的:

function createLRPadding($str, $chars = 20)
{
# Count the length
$strlen = strlen($str);
# Don't do anything if you are at the max characters
if($strlen >= $chars)
return $str;
# Get left and right balance
$len = ($chars - $strlen) / 2;
# Create fills on the left and right of the string and implode them to make one string
return implode('', array_fill(0,round($len, 0, PHP_ROUND_HALF_UP),'&nbsp;')).$str.implode('', array_fill(0,round($len, 0, PHP_ROUND_HALF_DOWN),'&nbsp;'));
}

使用:

echo createLRPadding('Cool string');

要调整填充,添加第二个参数:

echo createLRPadding('Cool string', 40);

第一个例子(默认 20 pad)会写:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Cool string&nbsp;&nbsp;&nbsp;&nbsp;

关于php - 在变量中添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142323/

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