Skip to content

Instantly share code, notes, and snippets.

@inkeliz
Last active October 15, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inkeliz/0dd973967ec1abf6cf1543e67814ffa4 to your computer and use it in GitHub Desktop.
Save inkeliz/0dd973967ec1abf6cf1543e67814ffa4 to your computer and use it in GitHub Desktop.
mb_str_pad
// This function need the mb_string;
// This function is based on the native str_pad from PHP (https://github.com/php/php-src/blob/master/ext/standard/string.c#L5332);
const STR_PAD_INSERT_ALL = 4;
function mb_str_pad(string $input, int $pad_length, string $pad_string, int $pad_type, string $pad_encoding = 'utf8') : string {
$result = '';
$pad_insert_all = 0;
$pad_inset_limit = 1;
$pad_str_len = mb_strlen($pad_string, $pad_encoding);
$input_len = mb_strlen($input, $pad_encoding);
if ($pad_length < 0 || $pad_length <= $input_len) {
return $input;
}
if(($pad_type & STR_PAD_INSERT_ALL) === STR_PAD_INSERT_ALL){
$pad_insert_all = PHP_INT_MAX;
$pad_inset_limit = null;
$pad_type -= STR_PAD_INSERT_ALL;
}
if ($pad_str_len === 0) {
trigger_error ( "Padding string cannot be empty", E_WARNING);
return $input;
}
if ($pad_type < STR_PAD_LEFT || $pad_type > STR_PAD_BOTH) {
trigger_error ("Padding type has to be STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH", E_WARNING);
return $input;
}
$num_pad_chars = $pad_length - $input_len;
if ($num_pad_chars >= PHP_INT_MAX) {
trigger_error ("Padding length is too long", E_WARNING);
return $input;
}
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;
}
for ($i = 0; $i < $left_pad; $i++){
$result .= mb_substr($pad_string, ($i % $pad_str_len) &~$pad_insert_all, $pad_inset_limit, $pad_encoding);
}
$result .= $input;
for ($i = 0; $i < $right_pad; $i++){
$result .= mb_substr($pad_string, ($i % $pad_str_len) &~$pad_insert_all, $pad_inset_limit, $pad_encoding);
}
return $result;
}
# Native str_pad:
$result = str_pad('漢字', 19, 'ç', STR_PAD_BOTH);
//= ççç漢字ççç�
# Custom mb_str_pad with multi-byte input and single multi-byte character pad:
$result = mb_str_pad('漢字', 19, 'ç', STR_PAD_BOTH, 'utf8');
//= çççççççç漢字ççççççççç
$result = mb_str_pad('漢字', 20, 'ç', STR_PAD_LEFT, 'utf8');
//= ççççççççççççççççç漢字
$result = mb_str_pad('漢字', 20, 'ç', STR_PAD_RIGHT, 'utf8');
//= 漢字çççççççççççççççççç
# Custom mb_str_pad with multi-byte input and multiples multi-bytes characters pad:
$result = mb_str_pad('漢字', 19, '$¬¬', STR_PAD_BOTH, 'utf8');
//= $¬¬$¬¬$¬漢字$¬¬$¬¬$¬¬
$result = mb_str_pad('漢字', 19, '$¬¬', STR_PAD_BOTH | STR_PAD_INSERT_ALL, 'utf8');
//= $¬¬$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬漢字$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬$¬¬
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment