note 71548 deleted from function.str-pad by bjori

From: Date: Tue, 05 Dec 2006 16:54:12 +0000
Subject: note 71548 deleted from function.str-pad by bjori
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-120309@lists.php.net to get a copy of this message
Note Submitter: Charles ---- Small correction to this otherwise good code (below). You must use mb_substr in case the pad-string is multibyte-encoded. If this is assumed to never be the case, then the code is trivial: <?php // pad-string is never multibyte: // function m_str_pad($ps_input, $pn_pad_length, $ps_pad_string = " ", $pn_pad_type = STR_PAD_RIGHT, $ps_encoding = NULL) { if (is_null($ps_encoding)) $ps_encoding = mb_internal_encoding(); return str_pad($ps_input, $pn_pad_length + strlen($ps_input) - mb_strlen($ps_input, $ps_encoding), $ps_pad_string, $pn_pad_type); } // pad-string possibly multibyte: // function m_str_pad($input, $pad_length, $pad_string = '', $pad_type = 1, $charset = null){ $str = ''; if ($charset==null) $charset = mb_internal_encoding(); $length = $pad_length - mb_strlen($input, $charset); $psLength = mb_strlen($pad_string); // pad string length if ($psLength<=0 OR $length<=0){ // pad string equal 0 $str = $input; }else{ // pad string AND space to padding is greater than 1 $repeatCount = floor($length/$psLength); // how many times repeat $lastStr = substr($pad_string, 0, $length%$psLength); // last part of pad string if($pad_type == STR_PAD_RIGHT){ $str = $input.str_repeat($pad_string, $repeatCount).$lastStr; } elseif($pad_type == STR_PAD_LEFT){ $str = str_repeat($pad_string, $repeatCount).$lastStr.$input; } elseif($pad_type == STR_PAD_BOTH){ $repeatCountLeft = 0; $repeatCountRight = 0; $lastStrLeft = ''; $lastStrRight = ''; if ($repeatCount%2==0){ // if is divisible 2 $repeatCountLeft = $repeatCountRight = floor($repeatCount/2); }else{ // if not - has to dive to 2 same parts $repeatCountLeft = $repeatCountRight = floor(($repeatCount-1)/2); } $lastStrLength = $length-2*$repeatCountLeft*$psLength; // the rest length to pad $lastStrLeftLength = $lastStrRightLength = floor($lastStrLength/2); // ther rest length divide to 2 parts $lastStrRightLength += $lastStrLength%2; // the last char add to right side $lastStrLeft = mb_substr($pad_string, 0, $lastStrLeftLength, $charset); $lastStrRight = mb_substr($pad_string, 0, $lastStrRightLength, $charset); $str = str_repeat($pad_string,$repeatCountLeft).$lastStrLeft; $str .= $input; $str .= str_repeat($pad_string,$repeatCountRight).$lastStrRight; } else{ $str = str_repeat($pad_string, $repeatCount).$lastStr.$input; } } return $str; } ?>

« previous php.notes (#120309) next »