note 69910 deleted from function.str-pad by danbrown
| From: | danbrown@php.net | Date: | Sat, 02 Jul 2011 18:55:12 +0000 |
| Subject: | note 69910 deleted from function.str-pad by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181190@lists.php.net to get a copy of this message | ||
Note Submitter: flap
----
here is some extension to Tomek Krzeminski example. It works correctly when length of pad_string is
greater than 1
(orig by Tomek Krzeminski)
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 = substr($pad_string, 0, $lastStrLeftLength);
$lastStrRight = substr($pad_string, 0, $lastStrRightLength);
$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;
}