Last Updated: February 25, 2016
·
4.11K
· roncsak

UTF-8 str_pad in PHP

Last day I had a problem with the standard strpad. I was using strings encoded in UTF-8. Oddly in some cases strpad did not padded a string to the given number. This function fixes this problem.

function mb_str_pad(
  $input,
  $pad_length,
  $pad_string=" ",
  $pad_style=STR_PAD_RIGHT,
  $encoding="UTF-8")
{
    return str_pad(
      $input,
      strlen($input)-mb_strlen($input,$encoding)+$pad_length,
      $pad_string,
      $pad_style);
}

Originally was posted here: PHP: str_pad - Manual