update page now

str_pad

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

str_pad使用另一个字符串填充字符串为指定长度

说明

str_pad(
    string $string,
    int $length,
    string $pad_string = " ",
    int $pad_type = STR_PAD_RIGHT
): string

该函数返回 string 被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的 pad_string 参数没有被指定,string 将被空格字符填充,否则它将被 pad_string 填充到指定长度。

参数

string

输入字符串。

length

填充字符串到最后的长度。 如果 length 的值是负数,小于或者等于输入字符串的长度,不会发生任何填充,并会返回 string

pad_string

注意:

如果填充字符的长度不能被 pad_string 整除,那么 pad_string 可能会被缩短。

pad_type

可选的 pad_type 参数的可能值为 STR_PAD_RIGHTSTR_PAD_LEFTSTR_PAD_BOTH。如果没有指定 pad_type,则假定它是 STR_PAD_RIGHT

返回值

返回填充后的字符串。

示例

示例 #1 str_pad() 示例

<?php
$input
= "Alien";
echo
str_pad($input, 10), PHP_EOL; // 输出 "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT), PHP_EOL; // 输出 "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH), PHP_EOL; // 输出 "__Alien___"
echo str_pad($input, 6, "___"), PHP_EOL; // 输出 "Alien_"
echo str_pad($input, 3, "*"), PHP_EOL; // 输出 "Alien"
?>

参见

  • mb_str_pad() - Pad a multibyte string to a certain length with another multibyte string

添加备注

用户贡献的备注 7 notes

up
108
Marjune
11 years ago
since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were always favor in the right pad if the required number of padding characters can't be evenly divided. 

e.g

<?php

echo str_pad("input", 10, "pp", STR_PAD_BOTH ); // ppinputppp
echo str_pad("input", 6, "p", STR_PAD_BOTH ); // inputp
echo str_pad("input", 8, "p", STR_PAD_BOTH ); //pinputpp

?>
up
4
neo_selen
5 years ago
you can use str_pad to display an integer with a fixed amount of digits, like that:
0002
0003
...
0100

by just writing

<?php
    for ($i=0;$i<10000;$i++){
        echo str_pad($i,4,'0',STR_PAD_LEFT)."\n";
    }
?>

i set 4 digits (see parameter #2), but you can set any fitting your needs.
up
7
Borszczuk
3 years ago
Beware, \str_pad() is NOT able to correctly handle multibyte characters and as \strlen() it is assuming one char ==  byte. If you have multibyte chars in your string your result string will be shorter than you expect:

<?php
$a = 'áč'; // 2 accented chars
$lenA = \mb_strlen($a);
echo $lenA . PHP_EOL;

$b = \str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;
?>

would produce:

2
10

instead of expected 12. There seem noth to be mb_str_pad() equivalent so you may end you concatenating your string and padding manually:

<?php
$a = 'áč'; // 2 accented chars

$b = mb_str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;

function mb_str_pad(string $str, int $len, string $pad, int $align = \STR_PAD_RIGHT): string
{
   $strLen = \mb_strlen($str);
   if ($strLen >= $len) {
      return $str;
   }

   $diff = $len - $strLen;
   $padding = \mb_substr(\str_repeat($pad, $diff), 0, $diff);

   switch ($align) {
      case \STR_PAD_BOTH:
         $diffHalf = (int)($diff/2 + 0.5);
         $padding = \str_repeat($pad, $diffHalf);
         $result = "{$padding}{$str}{$padding}";
         break;
      case \STR_PAD_LEFT:
         $result = "{$padding}{$str}";
         $result = "{$str}{$padding}";
         break;
      case \STR_PAD_RIGHT:
      default:
         $result = "{$str}{$padding}";
         break;
   }

   return \mb_substr($result, 0, $len);
}
?>

returns expected 12 char long string.
up
12
qeremy [atta] gmail [dotta] com
13 years ago
A proper unicode string padder;

<?php
mb_internal_encoding('utf-8'); // @important

function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
    $str_len = mb_strlen($str);
    $pad_str_len = mb_strlen($pad_str);
    if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
        $str_len = 1; // @debug
    }
    if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
        return $str;
    }
    
    $result = null;
    $repeat = ceil($str_len - $pad_str_len + $pad_len);
    if ($dir == STR_PAD_RIGHT) {
        $result = $str . str_repeat($pad_str, $repeat);
        $result = mb_substr($result, 0, $pad_len);
    } else if ($dir == STR_PAD_LEFT) {
        $result = str_repeat($pad_str, $repeat) . $str;
        $result = mb_substr($result, -$pad_len);
    } else if ($dir == STR_PAD_BOTH) {
        $length = ($pad_len - $str_len) / 2;
        $repeat = ceil($length / $pad_str_len);
        $result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length)) 
                    . $str 
                       . mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
    }
    
    return $result;
}
?>

Test;
<?php
// needs ie. "test.php" file encoded in "utf-8 without bom"
$s = '...';
for ($i = 3; $i <= 1000; $i++) {
    $s1 = str_pad($s, $i, 'AO', STR_PAD_BOTH); // can not inculde unicode char!!!
    $s2 = str_pad_unicode($s, $i, 'ÄÖ', STR_PAD_BOTH);
    $sl1 = strlen($s1);
    $sl2 = mb_strlen($s2);
    echo  "len $sl1: $s1 \n";
    echo  "len $sl2: $s2 \n";
    echo  "\n";
    if ($sl1 != $sl2) die("Fail!");
}
?>

Output;
len 3: ... 
len 3: ... 

len 4: ...A 
len 4: ...Ä 

len 5: A...A 
len 5: Ä...Ä 

len 6: A...AO 
len 6: Ä...ÄÖ 
...
up
3
robertwhishaw at gmail dot com
5 years ago
Incrementing or decrementing numbers in PHP is easy with the ++ and -- operators but it can be difficult to set the precision of the numbers. The str_pad() can be useful for concatenating a string to the beginning or end of the incrementing number to simulate a different precision. 

Good example, we want to increment 001 to 002, 003, 004:

$numbers = [];

for($i = 1; $i <= 4; $i++){
    $numbers[] = str_pad($i, 3, '0', STR_PAD_LEFT);
}

print_r($numbers);

$numbers[0] => '001',
$numbers[1] => '002',
$numbers[2] => '003',
$numbers[3] => '004',

Bad example, we want to increment 001 to 002, 003, 004 but if we set $i = 001 in the for() loop to start with, 001 will be converted to 1 and the incrementing will return: 1, 2, 3, 4 etc... 

$numbers = [];

for($i = 001; $i <= 4; $i++){
    $numbers[] = $i;
}

print_r($numbers);

$numbers[0] => 1,
$numbers[1] => 2,
$numbers[2] => 3,
$numbers[3] => 4,
up
7
wes at nospamplsexample dot org
11 years ago
multibyte version:

<?php
function mb_str_pad($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT, $encoding = NULL)
{
    $encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
    $padBefore = $dir === STR_PAD_BOTH || $dir === STR_PAD_LEFT;
    $padAfter = $dir === STR_PAD_BOTH || $dir === STR_PAD_RIGHT;
    $pad_len -= mb_strlen($str, $encoding);
    $targetLen = $padBefore && $padAfter ? $pad_len / 2 : $pad_len;
    $strToRepeatLen = mb_strlen($pad_str, $encoding);
    $repeatTimes = ceil($targetLen / $strToRepeatLen);
    $repeatedString = str_repeat($pad_str, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
    $before = $padBefore ? mb_substr($repeatedString, 0, floor($targetLen), $encoding) : '';
    $after = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLen), $encoding) : '';
    return $before . $str . $after;
}
?>
up
3
bob [at] bobarmadillo [dot] com
23 years ago
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:

<?php
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";
?>
To Top