Skip to content

New function mb_str_pad (multibyte str_pad) #10203

Closed
@aetonsi

Description

@aetonsi

Description

Hello,

I'd like to propose a new function. Amidst all of the mb_*** versions of the string functions, i noticed that one is missing: str_pad.
Something that would allow to do this:

mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_RIGHT);
mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_LEFT);
mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_BOTH);

and get this

▶▶❤❓❇❤
❤❓❇❤▶▶
❤❓▶▶❤❓

It could be as simple as this:

function mb_str_pad(
    string $string,
    int $length,
    string $pad_string = " ",
    int $pad_type = STR_PAD_RIGHT,
    string|null $encoding = null
) {
    $padding = '';
    $paddingLength = $length - mb_strlen($string, $encoding);
    while (($l = mb_strlen($padding, $encoding)) < $paddingLength) {
        // build padding string 1 $pad_string at a time until the desired $paddingLength is reached
        $padding .= mb_substr($pad_string, 0, $paddingLength - $l, $encoding);
    }
    return match ($pad_type) {
        STR_PAD_RIGHT => $string . $padding,
        STR_PAD_LEFT => $padding . $string,
        STR_PAD_BOTH =>
        mb_substr($padding, 0, ceil(mb_strlen($padding, $encoding) / 2)) .
            $string .
            mb_substr($padding, 0, floor(mb_strlen($padding, $encoding) / 2)),
    };
}

...obviously this is just an example, it's not optimized, it doesn't consider errors, etc


Have a nice day

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions