Last active
June 7, 2023 15:53
-
-
Save MakStashkevich/31f5cb7b229bc735aeaa89a6796327ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Multibyte String Pad | |
* | |
* Functionally, the equivalent of the standard str_pad function, but is capable of successfully padding multibyte strings. | |
* | |
* @param string $input The string to be padded. | |
* @param int $pad_length The length of the resultant padded string. | |
* @param string $pad_string The string to use as padding. Defaults to space. | |
* @param int $pad_type The type of padding. Defaults to STR_PAD_RIGHT. | |
* @param string $encoding The encoding to use, defaults to UTF-8. | |
* | |
* @return string A padded multibyte string. | |
*/ | |
function mb_str_pad(string $input, int $pad_length, string $pad_string = "\x20", int $pad_type = STR_PAD_RIGHT, string $encoding = 'UTF-8') | |
{ | |
$input_length = mb_strlen($input, $encoding); | |
$pad_string_length = mb_strlen($pad_string, $encoding); | |
if ($pad_length <= 0 || ($pad_length - $input_length) <= 0) { | |
return $input; | |
} | |
$num_pad_chars = $pad_length - $input_length; | |
switch ($pad_type) { | |
case STR_PAD_RIGHT: | |
$left_pad = 0; | |
$right_pad = $num_pad_chars; | |
break; | |
case STR_PAD_LEFT: | |
$left_pad = $num_pad_chars; | |
$right_pad = 0; | |
break; | |
case STR_PAD_BOTH: | |
$left_pad = floor($num_pad_chars / 2); | |
$right_pad = $num_pad_chars - $left_pad; | |
break; | |
} | |
$result = ''; | |
for ($i = 0; $i < $left_pad; ++$i) { | |
$result .= mb_substr($pad_string, $i % $pad_string_length, 1, $encoding); | |
} | |
$result .= $input; | |
for ($i = 0; $i < $right_pad; ++$i) { | |
$result .= mb_substr($pad_string, $i % $pad_string_length, 1, $encoding); | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment