str_pad

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

str_padДополняет строку другой строкой до заданной длины

Описание

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Эта функция возвращает строку input, дополненную слева, справа или с обоих сторон до заданной длины. Если необязательный аргумент pad_string не передан, то input будет дополнен пробелами, иначе он будет дополнен символами из pad_string до нужной длины

Список параметров

input

Входная строка.

pad_length

Если значение pad_length отрицательно, меньше или равно длине входной строки, то дополнения не происходит.

pad_string

Замечание:

pad_string может быть урезана, если необходимое количество дополняемых символов не делится нацело на длину строки pad_string.

pad_type

Необязательный аргумент pad_type может иметь значение STR_PAD_RIGHT, STR_PAD_LEFT или STR_PAD_BOTH. Если не указан, то по умолчанию используется STR_PAD_RIGHT.

Возвращаемые значения

Возвращает дополненную строку.

Примеры

Пример #1 Пример использования str_pad()

<?php
$input 
"Alien";
echo 
str_pad($input10);                      // выводит "Alien     "
echo str_pad($input10"-="STR_PAD_LEFT);  // выводит "-=-=-Alien"
echo str_pad($input10"_"STR_PAD_BOTH);   // выводит "__Alien___"
echo str_pad($input"___");               // выводит "Alien_"
?>

Коментарии

For me this worked.
$string = 'help';

#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';

#Second, str_replace with '&nbsp;'
$string = str_replace("*", "&nbsp;", $string);
2002-06-06 07:26:44
http://php5.kiev.ua/manual/ru/function.str-pad.html
When provided with a string of characters as the pad value, str_pad uses all the characters as fill, and can leave partial strings. (eg. If the pad value is 'ABC' and it needs 5 characters to pad with, it outputs 'ABCAB'.) This is a problem when you want to pad with non-breaking spaces, the code for which is 6 characters long. 

This can be resolved by first padding the string with a single character that won't be found in the strings such as * then doing a str_replace of * with &nbsp;.
2002-08-20 14:23:34
http://php5.kiev.ua/manual/ru/function.str-pad.html
Basically, *all* of you guys have a 'long' way of padding text with html tags (which includes &nbsp;) You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:
<?
  $text 
"This is pretty interesting!";
 
$pad_string "&nbsp;";
 
 
//Pad text on both sides 
 
$text str_pad($textstrlen($text)+(20*strlen($pad_string)), $pad_stringSTR_PAD_BOTH);
  print 
$text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
2002-12-02 04:22:43
http://php5.kiev.ua/manual/ru/function.str-pad.html
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_stringfloor($length/2));
   
$str .= $input;
   
$str .= str_repeat($pad_stringceil($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_me20' ')."|\n";
echo 
'|'.full_str_pad($pad_me20' 'STR_PAD_RIGHT)."|\n";
echo 
'|'.full_str_pad($pad_me20' 'STR_PAD_BOTH)."|\n";
?>
2002-12-03 11:22:49
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
<?php
   
/**
     * str_pad_html - Pad a string to a certain length with another string.
     * accepts HTML code in param: $strPadString.
     * 
     * @name        str_pad_html()
     * @author        Tim Johannessen <root@it.dk>
     * @version        1.0.0
     * @param        string    $strInput    The array to iterate through, all non-numeric values will be skipped.
     * @param        int    $intPadLength    Padding length, must be greater than zero.
     * @param        string    [$strPadString]    String to pad $strInput with (default: &nbsp;)
     * @param        int        [$intPadType]        STR_PAD_LEFT, STR_PAD_RIGHT (default), STR_PAD_BOTH
     * @return        string    Returns the padded string
    **/
   
function str_pad_html($strInput ""$intPadLength$strPadString "&nbsp;"$intPadType STR_PAD_RIGHT) {
        if (
strlen(trim(strip_tags($strInput))) < intval($intPadLength)) {
           
            switch (
$intPadType) {
                 
// STR_PAD_LEFT
               
case 0:
                   
$offsetLeft intval($intPadLength strlen(trim(strip_tags($strInput))));
                   
$offsetRight 0;
                    break;
                   
               
// STR_PAD_RIGHT
               
case 1:
                   
$offsetLeft 0;
                   
$offsetRight intval($intPadLength strlen(trim(strip_tags($strInput))));
                    break;
                   
               
// STR_PAD_BOTH
               
case 2:
                   
$offsetLeft intval(($intPadLength strlen(trim(strip_tags($strInput)))) / 2);
                   
$offsetRight round(($intPadLength strlen(trim(strip_tags($strInput)))) / 20);
                    break;
                   
               
// STR_PAD_RIGHT
               
default:
                   
$offsetLeft 0;
                   
$offsetRight intval($intPadLength strlen(trim(strip_tags($strInput))));
                    break;
            }
           
           
$strPadded str_repeat($strPadString$offsetLeft) . $strInput str_repeat($strPadString$offsetRight);
            unset(
$strInput$offsetLeft$offsetRight);
           
            return 
$strPadded;
        }
       
        else {
            return 
$strInput;
        }
    }

?>
2005-03-28 00:28:08
http://php5.kiev.ua/manual/ru/function.str-pad.html
I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.

<?php

$str 
"test";

function 
str_pad_right $string $padchar $int ) {
   
$i strlen $string ) + $int;
   
$str str_pad $string $i $padchar STR_PAD_RIGHT );
    return 
$str;
}
   
function 
str_pad_left $string $padchar $int ) {
   
$i strlen $string ) + $int;
   
$str str_pad $string $i $padchar STR_PAD_LEFT );
    return 
$str;
}
   
function 
str_pad_both $string $padchar $int ) {
   
$i strlen $string ) + ( $int );
   
$str str_pad $string $i $padchar STR_PAD_BOTH );
    return 
$str;
}

echo 
str_pad_left $str "-" ); // Produces: ---test
echo str_pad_right $str "-" ); // Produces: test---
echo str_pad_both $str "-" ); // Produces: ---test---
?>

Hope this can help someone!
2005-08-10 08:04:20
http://php5.kiev.ua/manual/ru/function.str-pad.html
Hello,

for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments.

<?php

$string 
'this is a test';
$oldLen strlen($string);
$direction STR_PAD_BOTH;
echo 
$string.'<br>';
echo 
str_const_len($string101'#'$direction).'<br>';
echo 
$string.'<br>';
echo 
str_const_len($string$oldLen'#'$direction).'<br>';
echo 
$string.'<br><br>'."\n";

   
   
/*     This function is an extension to str_pad, it manipulates the referenced
    string '$str' and stretches or reduces it to the specified length. It
    returns the number of characters, that were added or stripped. */
function str_const_len(&$str$len$char ' '$str_pad_const STR_PAD_RIGHT) {
   
$origLen strlen($str);
    if (
strlen($str) < $len) {     /* stretch string */
       
$str str_pad($str$len$char$str_pad_const);
    }
    else {                         
/* reduce string */
       
switch ($str_pad_const) {
            case 
STR_PAD_LEFT:
               
$str substr($str, (strlen($str) - $len), $len);
                break;
            case 
STR_PAD_BOTH:
               
$shorten = (int) ((strlen($str) - $len) / 2);
               
$str substr($str$shorten$len);
                break;
            default:
               
$str substr($str0$len);
                break;
        }
    }
    return (
$len $origLen);
}
?>
2005-11-15 10:43:50
http://php5.kiev.ua/manual/ru/function.str-pad.html
Fills the first argument (mostly a number, f.e. from a <select> loop to display a date or time) with zeroes.

<?php
function zerofill($mStretch$iLength 2)
{
   
$sPrintfString '%0' . (int)$iLength 's';
    return 
sprintf($sPrintfString$mStretch);
}
?>

sprintf() is indeed faster than str_pad.
2007-04-01 13:43:56
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
Warning: If your string includes non-ascii characters (eg the British pounds sign), str_pad() will treat these as two characters when calculating the padding.

So for example:
<?php
str_pad
($currency_symbol.$showtottopay,12," ",STR_PAD_LEFT);
?>
will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.
2007-07-18 11:47:54
http://php5.kiev.ua/manual/ru/function.str-pad.html
In case you want to pad 2 strings together with a character you can use:

<?php
function pad_between_strings($string1$string2$length$char " ") {
   
$fill_length $length - ( strlen($string1) + strlen($string2) );
    return 
$string1 str_repeat($char$fill_length) . $string2;
}
?>
2008-03-20 08:17:20
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432

<?php

function number_pad($number,$n) {
return 
str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

?>

$n indicates how many characters you want.
2008-10-16 14:28:10
http://php5.kiev.ua/manual/ru/function.str-pad.html
Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "åäöÅÄÖ" that are double byte in UTF-8.

<?php
function mb_str_pad($input$pad_length$pad_string=' '$pad_type=STR_PAD_RIGHT) {
   
$diff strlen($input) - mb_strlen($input);
    return 
str_pad($input$pad_length+$diff$pad_string$pad_type);
}
?>
2009-03-21 08:43:14
http://php5.kiev.ua/manual/ru/function.str-pad.html
This is how I pad using &nbsp; :

str_replace(" ", "&nbsp;&nbsp;", str_pad($foo, 10, " ", STR_PAD_LEFT))

Seems to work well using two &nbsp; tags for each character added, at least for my use. YMMV.
2011-09-25 00:18:15
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
2011-10-12 05:45:42
http://php5.kiev.ua/manual/ru/function.str-pad.html
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($result0$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), 0floor($length)) 
                    . 
$str 
                       
mb_substr(str_repeat($pad_str$repeat), 0ceil($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: Ä...ÄÖ 
...
2013-01-20 03:44:44
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
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

?>
2014-11-17 17:45:41
http://php5.kiev.ua/manual/ru/function.str-pad.html
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 $pad_len;
   
$strToRepeatLen mb_strlen($pad_str$encoding);
   
$repeatTimes ceil($targetLen $strToRepeatLen);
   
$repeatedString str_repeat($pad_strmax(0$repeatTimes)); // safe if used with valid utf-8 strings
   
$before $padBefore mb_substr($repeatedString0floor($targetLen), $encoding) : '';
   
$after $padAfter mb_substr($repeatedString0ceil($targetLen), $encoding) : '';
    return 
$before $str $after;
}
?>
2014-11-28 20:29:56
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
a different, more robust multibyte version of str_pad that works correctly only if $pad_string is non-multibyte string

function my_mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT,$encoding='UTF-8'){
    $mb_diff=mb_strlen($str, $encoding)-strlen($string);       
    return str_pad($input,$pad_length+$mb_diff,$pad_string,$pad_type);
}
2015-01-29 18:04:54
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
For simple padding, you can use sprintf, which is faster:
see http://php.net/sprintf Example #5 "Specifying padding character"
2015-07-20 02:13:56
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
Here is the mcinp's version of mb_str_pad bugfixed: 

<?php
function mb_str_pad($input$pad_length$pad_string=' '$pad_type=STR_PAD_RIGHT,$encoding='UTF-8'){
       
$mb_diff=mb_strlen($input$encoding)-strlen($input);
        return 
str_pad($input,$pad_length-$mb_diff,$pad_string,$pad_type);
    } 
?> 

Still working correctly only if $pad_string is non-multibyte string
2016-03-11 12:25:59
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
sprintf is faster

$sTime = microtime(true);
$s = sprintf("%'-1000000s", '-');
$eTime = microtime(true);
echo 'sprintf ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

$sTime = microtime(true);
$s = str_pad('-', 1000000, '-');
$eTime = microtime(true);
echo 'str_pad ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

//result
sprintf ran in 2.0260810852051 milliseconds
str_pad ran in 26.59797668457 milliseconds
2017-01-10 04:52:18
http://php5.kiev.ua/manual/ru/function.str-pad.html
// Columnizer: add padding into text columns according maximum column size.
// sample input:
$a='[1515] -> ID=1515 / post_date=2012-06-18 04:48:47 / post_name=review-terminatrix-by-sfam 
    [177] -> ID=177 / post_date=2017-05-12 12:12:03 / post_name=review-the-terminator-by-sfam 
    [228621100] -> ID=2286 / post_date=2012-06-18 04:48:32 / post_name=terminator-3-rise-of-the-machines-2003';

function columnize($input, $separator=" "){
    $lines = explode("\n", $input);
    foreach ($lines as $k=>$line){
      $r[$k] = explode(" ", trim($line));
    }
    // print_r($r);
    $nc = sizeOf($r[0]);
    // echo $nc;
    for($i=0;$i<$nc;$i++){
      $col[$i] = array_column($r, $i);
      }
    // print_r($col);
    for ($i=0;$i<sizeof($col);$i++){
      $maxlen = max(array_map('strlen', $col[$i]));
      $tam[$i]=$maxlen;
      // echo "$i:$maxlen".PHP_EOL;
      $cs[$i]=$maxlen;
    }
    // print_r($cs);
    $o="";
    for ($r=0;$r<sizeOf($lines);$r++){
      for ($c=0;$c<sizeof($cs);$c++){
        $o.= str_pad($col[$c][$r], $cs[$c]+2, " ", STR_PAD_RIGHT );
      }
      $o .= PHP_EOL;
    }   
    return $o;
  }

echo $columnize($a);
// will output text nicely in columns :)
2017-06-12 19:35:36
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
sprintf() is not always faster... It certainly scales a lot better then str_pad so when running a benchmark that pads 10k characters,  sprintf will come out on top. But if you benchmarked a more real world scenario, it seems str_pad comes out the clear winner.

$sTime = microtime(true);
$count = 5;
$s = sprintf("%'\n5s", "\n");
$eTime = microtime(true);
echo 'sprintf ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

$sTime = microtime(true);
$s = str_pad("\n", 5, "\n");
$eTime = microtime(true);
echo 'str_pad ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

sprintf ran in 0.015974044799805 milliseconds
str_pad ran in 0.0059604644775391 milliseconds
2017-08-07 00:32:20
http://php5.kiev.ua/manual/ru/function.str-pad.html
str_pad() can provide sufficient "zero padding" when using block ciphers and manual padding with openssl_encrypt() and similar.

The example below will pad the 6 character text "Secret" with two \x00 characters and return 8 characters of data. Substitute your plain text and block size as needed.

<?php
$text 
"Secret";
$block_size 8;
$length ceil(strlen($text) / $block_size) * $block_size;
$data str_pad($text$length"\x00");
2019-12-07 20:53:09
http://php5.kiev.ua/manual/ru/function.str-pad.html
how to add some 0 before numbers
for example 5  ===> 005

do something like this:

echo str_pad(5,3,0,STR_PAD_LEFT); // result 005

echo str_pad(4,6,0,STR_PAD_LEFT); // result 000005
2020-06-02 12:07:21
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
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.
2020-06-04 17:11:46
http://php5.kiev.ua/manual/ru/function.str-pad.html
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,
2020-06-07 06:44:49
http://php5.kiev.ua/manual/ru/function.str-pad.html
Автор:
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 $strint $lenstring $padint $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/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($result0$len);
}
?>

returns expected 12 char long string.
2022-10-18 18:04:26
http://php5.kiev.ua/manual/ru/function.str-pad.html

    Поддержать сайт на родительском проекте КГБ