note 69910 added to function.str-pad
| From: | flap at osu1 dot php dot net | Date: | Tue, 26 Sep 2006 08:59:00 +0000 |
| Subject: | note 69910 added to function.str-pad | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-117674@lists.php.net to get a copy of this message | ||
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;
}
----
Server IP: 62.65.181.66
Probable Submitter: 84.16.33.226
----
Manual Page -- http://www.php.net/manual/en/function.str-pad.php
Edit -- https://master.php.net/note/edit/69910
Del: integrated -- https://master.php.net/note/delete/69910/integrated
Del: useless -- https://master.php.net/note/delete/69910/useless
Del: bad code -- https://master.php.net/note/delete/69910/bad+code
Del: spam -- https://master.php.net/note/delete/69910/spam
Del: non-english -- https://master.php.net/note/delete/69910/non-english
Del: in docs -- https://master.php.net/note/delete/69910/in+docs
Del: other reasons-- https://master.php.net/note/delete/69910
Reject -- https://master.php.net/note/reject/69910
Search -- https://master.php.net/manage/user-notes.php