update page now

Voting

: two minus two?
(Example: nine)

The Note You're Voting On

Borszczuk
3 years ago
Beware, \str_pad() is NOT able to correctly handle multibyte characters and as \strlen() it is assuming one char ==  byte. If you have multibyte chars in your string your result string will be shorter than you expect:

<?php
$a = 'áč'; // 2 accented chars
$lenA = \mb_strlen($a);
echo $lenA . PHP_EOL;

$b = \str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;
?>

would produce:

2
10

instead of expected 12. There seem noth to be mb_str_pad() equivalent so you may end you concatenating your string and padding manually:

<?php
$a = 'áč'; // 2 accented chars

$b = mb_str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;

function mb_str_pad(string $str, int $len, string $pad, int $align = \STR_PAD_RIGHT): string
{
   $strLen = \mb_strlen($str);
   if ($strLen >= $len) {
      return $str;
   }

   $diff = $len - $strLen;
   $padding = \mb_substr(\str_repeat($pad, $diff), 0, $diff);

   switch ($align) {
      case \STR_PAD_BOTH:
         $diffHalf = (int)($diff/2 + 0.5);
         $padding = \str_repeat($pad, $diffHalf);
         $result = "{$padding}{$str}{$padding}";
         break;
      case \STR_PAD_LEFT:
         $result = "{$padding}{$str}";
         $result = "{$str}{$padding}";
         break;
      case \STR_PAD_RIGHT:
      default:
         $result = "{$str}{$padding}";
         break;
   }

   return \mb_substr($result, 0, $len);
}
?>

returns expected 12 char long string.

<< Back to user notes page

To Top