note 27364 added to function.str-pad
| From: | bob at rack1 dot php dot net | Date: | Tue, 03 Dec 2002 15:22:49 +0000 |
| Subject: | note 27364 added to function.str-pad | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-40298@lists.php.net to get a copy of this message | ||
In a lot of cases you're better off using str_repeat if you want to use something like
- it repeats the entire string.
Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every
other way:
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
$str = '';
$length = $pad_length - strlen($input);
if ($length > 0) { // str_repeat doesn't like negatives
if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
$str = $input.str_repeat($pad_string, $length);
} elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
$str = str_repeat($pad_string, floor($length/2));
$str .= $input;
$str .= str_repeat($pad_string, ceil($length/2));
} else { // defaults to STR_PAD_LEFT == 0
$str = str_repeat($pad_string, $length).$input;
}
} else { // if $length is negative or zero we don't need to do anything
$str = $input;
}
return $str;
}
$pad_me = "Test String";
echo '|'.full_str_pad($pad_me, 20, ' ')."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_RIGHT)."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_BOTH)."|\n";
--
http://www.php.net/manual/en/function.str-pad.php
http://master.php.net/manage/user-notes.php?action=edit+27364
http://master.php.net/manage/user-notes.php?action=delete+27364
http://master.php.net/manage/user-notes.php?action=reject+27364