Вы можете использовать все собственные функции для достижения этой цели:
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