note 104717 deleted from function.str-pad by danbrown

From: Date: Sat, 02 Jul 2011 18:32:42 +0000
Subject: note 104717 deleted from function.str-pad by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181181@lists.php.net to get a copy of this message
Note Submitter: fabien dot villepinte at gmail dot com ---- The Vasu's solution doesn't work well if $pad_string contains multibyte characters. Here another way to implement it: <?php function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) { $diff = $pad_length - mb_strlen($input, 'UTF-8'); if ($diff <= 0) { return $input; } $pad_string = str_pad($pad_string, 1); $multiplier = ceil($diff / mb_strlen($pad_string, 'UTF-8')); $compl = mb_substr(str_repeat($pad_string, $multiplier), 0, $diff, 'UTF-8'); if ($pad_type === STR_PAD_LEFT) { return $compl.$input; } elseif ($pad_type === STR_PAD_BOTH) { return mb_substr($compl, -1, round($diff/2), 'UTF-8') .$input .mb_substr($compl, 0, ceil($diff/2), 'UTF-8'); } else { return $input.$compl; } } echo mb_str_pad('ë', 4, 'éè', STR_PAD_BOTH); // éëéè ?>

« previous php.notes (#181181) next »