note 127742 added to function.str-pad

From: Date: Tue, 18 Oct 2022 15:04:26 +0000
Subject: note 127742 added to function.str-pad
Groups: php.notes 
Request: Send a blank email to php-notes+get-219693@lists.php.net to get a copy of this message
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. ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.159.161 (proxied: 2a00:f41:3881:99d2:9f89:7f86:8ca3:5e0d) ---- Manual Page -- https://php.net/manual/en/function.str-pad.php Edit -- https://main.php.net/note/edit/127742 Del: integrated -- https://main.php.net/note/delete/127742/integrated Del: useless -- https://main.php.net/note/delete/127742/useless Del: bad code -- https://main.php.net/note/delete/127742/bad+code Del: spam -- https://main.php.net/note/delete/127742/spam Del: non-english -- https://main.php.net/note/delete/127742/non-english Del: in docs -- https://main.php.net/note/delete/127742/in+docs Del: other reasons-- https://main.php.net/note/delete/127742 Reject -- https://main.php.net/note/reject/127742 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219693) next »