[php-src] Issue #10203: New function mb_str_pad (multibyte str_pad)
| From: | aetonsi | Date: | Sun, 01 Jan 2023 22:38:46 +0000 |
| Subject: | [php-src] Issue #10203: New function mb_str_pad (multibyte str_pad) | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-243308@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/10203
Author: 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:
```php
mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_RIGHT);
mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_LEFT);
mb_str_pad('▶▶', 6, '❤❓❇', STR_PAD_BOTH);
```
and get this
```log
▶▶❤❓❇❤
❤❓❇❤▶▶
❤❓▶▶❤❓
```
It could be as simple as this:
```php
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