str_pad

(PHP 4 >= 4.0.1, PHP 5)

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 を指定可能です。 pad_typeが指定されない場合、 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_"
?>

add a note add a note

User Contributed Notes 27 notes

up
10
david dot rensonnet at swing dot be
11 years ago
my solution to saveloywill at netscape dot net:

$myvar2="Alien";
$myvar=str_pad($myvar2,15," ",STR_PAD_RIGHT);
$myvar=str_replace(" ","&nbsp;",$myvar);

this way, only complete spaces will show up.

enjoy!
david rensonnet
up
5
bxi at apparoat dot nl
6 years ago
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;
}
?>
up
3
Fahad dot Gilani at anu dot edu dot au
11 years ago
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($text, strlen($text)+(20*strlen($pad_string)), $pad_string, STR_PAD_BOTH);
  print $text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
up
2
pestilenc at hotmail dot com
12 years ago
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);
up
4
cj at NOSPAM dot ceejayoz dot com
12 years ago
Another solution to no_email@php.net's problem would be to simply multiply the padding string by 6.

e.g.

$string = str_pad($string, 10, "&nbsp;", STR_PAD_BOTH);

becomes

$string = str_pad($string, 60, "&nbsp;", STR_PAD_BOTH);

which will avoid problems with the above solution, which will mess up text that has the * in it (or whichever character you're replacing)
up
2
christian dot reinecke at web dot de
7 years ago
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.
up
1
saveloywill at netscape dot net
12 years ago
Here is my solution to the above problem.
Simply place the code in question inbetween  html <pre> tags, like this:

<?php
print "<pre>";
$input = "Alien";
print
str_pad($input, 10);
print
"*";
print
"</pre>";
?>

Thanks.
up
1
private dot email at optusnet dot com dot au
9 years ago
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 * 2 );
   
$str = str_pad ( $string , $i , $padchar , STR_PAD_BOTH );
    return
$str;
}

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

Hope this can help someone!
up
1
Spudley
7 years ago
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.
up
1
matrebatre
6 years ago
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.
up
1
Marjune
10 days 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
0
nehuensd at gmail dot com
6 months ago
if the length of the pad is less than or equal to the string, the original string will be returned
<?php
   
echo(str_pad("abcd", 2, "-", STR_PAD_LEFT)."<br>");
    echo(
str_pad("abcd", 4, "-", STR_PAD_LEFT)."<br>");
    echo(
str_pad("abcd", 6, "-", STR_PAD_LEFT)."<br>");

Output:
abcd
abcd
--abcd
up
0
qeremy [atta] gmail [dotta] com
1 year 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
0
gene at swipesy dot com
3 years ago
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.
up
0
Silvio Ginter (silvio dot ginter at gmx dot de)
9 years ago
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($string, 101, '#', $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($str, 0, $len);
                break;
        }
    }
    return (
$len - $origLen);
}
?>
up
0
zubfatal <root at it dot dk>
9 years ago
<?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)))) / 2, 0);
                    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;
        }
    }

?>
up
0
bob [at] bobarmadillo [dot] com
11 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";
?>
up
0
pozytron#mac#com
12 years ago
The trouble with cj@NOSPAM.ceejayoz.com's version over pestilenc@hotmail.com's is that many of the times it is used, it will end up with fragments of the "&nbsp;" code.

For example, the following code:
<?php
echo str_pad("TESTSTRING",60,"&nbsp;",STR_PAD_BOTH);
?>

produces the following HTML output:
&nbsp;&nbsp;&nbsp;&nbsp;&TESTSTRING&nbsp;&nbsp;&nbsp;&nbsp;&
up
-1
Kari &#34;Haprog&#34; Sderholm
5 years ago
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);
}
?>
up
-2
mreilly at NOSPAM dot mac dot com
12 years ago
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;.
up
-1
jared at dctkc dot com
12 years ago
matthew.somerville's code did NOT work for me.
neither did bert@catsburg.com's.
neither did any other documentation.
(if I isolated the code by itself, they all worked; but in the context I was using it, $value was numeric, and there is NO WAY to force it to be a string in PHP).

I had to roll my own. I used 'trim' to _force_
the value of $value to be string, because as
long as PHP thought it was numeric, I could
not use any form of left-padding with zeros.

This worked (I use sprintf to left-pad
$value with zeros to a length of 4):

sprintf("%04s",trim($value));
up
-3
matthew dot somerville at trinity dot oxford dot ac dot uk
13 years ago
I find:

$mystr = substr("0000$mystr",-4)

(where the 0s are padding characters and -4 is the negative of the maxlength to pad to) is even simpler.
up
-5
sergey
3 years ago
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
up
-3
Balthazar Mondragoni
10 months ago
A heads up - warning for new coders:

STR_PAD_RIGHT,    STR_PAD_LEFT and   STR_PAD_BOTH
must be used  in UPPER CASE.

I've added this because the documentation at the top of the page doesn't make it explicit, and a few of my students have scratched their heads for half-an-hour or more because they couldn't figure it out.
up
-3
Mohammad Nabil
11 months ago
To pad with complete HTML &amp; or &nbsp;

function padString($string, $repetition, $count, $direction) {
        $length = strlen($string);
       
        for ($i = 0; $i < $count - $length; $i++) {
            if ($direction == STR_PAD_LEFT) {
                $string = $repetition . $string;
            } else {//STR_PAD_RIGHT
                $string = $string . $repetition;
            }
        }
        return $string;
    }

padString("Text",  "&nbsp;", 10, STR_PAD_LEFT)
up
-4
Balthazar Mondragoni
10 months ago
A heads up - warning for new coders:

STR_PAD_RIGHT,    STR_PAD_LEFT and   STR_PAD_BOTH
must be used  in UPPER CASE.

I've added this because the documentation at the top of the page doesn't make it explicit, and a few of my students have scratched their heads for half-an-hour or more because they couldn't figure it out.
up
-5
no_email at php dot net
12 years ago
To convert your string couldnt you just use strval($var)?

What if you want non-breaking spaces? If I try to str_pad with "&nbsp;" PHP thinks my padding string is 6 characters, whn in HTML it is only one.
To Top