您可以使用所有本机函数来实现此目的:
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),' ')).$str.implode('', array_fill(0,round($len, 0, PHP_ROUND_HALF_DOWN),' '));
}
要使用:
echo createLRPadding('Cool string');
要调整填充,请添加第二个参数:
echo createLRPadding('Cool string', 40);
第一个例子(默认 20 pad)会写:
Cool string