mb_str_pad

mb_str_pad($string, $length, $pad_string, $pad_type, $encoding)

Pads a string with a fill to the given number of characters. Unlike str_pad() it counts characters, so it aligns accented text correctly. The function exists since PHP 8.3.

Parameters

  • $string – the string to pad.
  • $length – the resulting length in characters. When the string is longer, it is returned unchanged.
  • $pad_string – optional, the fill characters. The default is a space.
  • $pad_type – optional, STR_PAD_RIGHT (default), STR_PAD_LEFT or STR_PAD_BOTH.
  • $encoding – optional, the character encoding. The default comes from mb_internal_encoding().

Examples

echo mb_str_pad("Café", 6, "."); // Café..
// str_pad counts bytes – é has two of them in UTF-8
echo str_pad("Café", 6, "."); // Café.
echo mb_str_pad("42", 5, "0", STR_PAD_LEFT); // 00042
echo mb_str_pad("Résumé", 12, "*", STR_PAD_BOTH); // ***Résumé***
// columns in plain text (e-mail, console output)
echo mb_str_pad("Café", 10, ".") . mb_str_pad("€4.50", 7, " ", STR_PAD_LEFT); // Café......  €4.50
echo mb_str_pad("Éclair", 10, ".") . mb_str_pad("€6.00", 7, " ", STR_PAD_LEFT); // Éclair....  €6.00

Fallback for older PHP

The function does not exist in versions older than PHP 8.3. The following code adds it only where it is missing, newer versions use the built-in function.

if (!function_exists("mb_str_pad")) {
    function mb_str_pad($string, $length, $pad_string = " ", $pad_type = STR_PAD_RIGHT, $encoding = "UTF-8") {
        $missing = $length - mb_strlen($string, $encoding);
        if ($missing <= 0 || $pad_string === "") {
            return $string;
        }
        $left = $pad_type === STR_PAD_LEFT ? $missing : ($pad_type === STR_PAD_BOTH ? intdiv($missing, 2) : 0);
        $repeat = function ($count) use ($pad_string, $encoding) {
            return mb_substr(str_repeat($pad_string, $count), 0, $count, $encoding);
        };
        return $repeat($left) . $string . $repeat($missing - $left);
    }
}
echo mb_str_pad("Café", 6, "."); // Café..
echo mb_str_pad("Résumé", 12, "*", STR_PAD_BOTH); // ***Résumé***

Things to watch out for

  • An empty fill throws a ValueError. The fallback above returns the string unchanged in that case.
  • With STR_PAD_BOTH and an odd number of missing characters the right side gets one character more.
  • Aligned columns work only with a monospaced font. Wide characters (Chinese, Japanese) take two positions, for them there are mb_strwidth() and mb_strimwidth().

Related functions:
str_pad()
mb_strlen()
mb_strimwidth()
sprintf()