search for in the  
<str_ireplacestr_repeat>
Last updated: Thu, 19 May 2005

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_pad --  Pad a string to a certain length with another string

Description

string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]] )

This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

Example 1. str_pad() example

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

Note: The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.



User Contributed Notes
str_pad
Anloc <info NOSPAM at anloc dot net>
19-May-2005 11:41
Tomek Krzeminski's iconv_str_pad modified for php 4 (iconv_strlen only works for php 5) courtesy of www.anloc.net

   function iconv_str_pad( $input, $pad_length, $pad_string = '', $pad_type = 1, $charset = "UTF-8" )
   {
       $str = '';
//      $length = $pad_length - iconv_strlen( $input, $charset );
       $length = $pad_length - preg_match_all('/./u', $input, $dummy);
       if( $length > 0)
       {
           if( $pad_type == STR_PAD_RIGHT )
           {
               $str = $input . str_repeat( $pad_string, $length );
           } elseif( $pad_type == STR_PAD_LEFT )
           {
               $str = str_repeat( $pad_string, $length ) . $input;
           } elseif( $pad_type == STR_PAD_BOTH )
           {
               $str = str_repeat( $pad_string, floor( $length / 2 ));
               $str .= $input;
               $str .= str_repeat( $pad_string, ceil( $length / 2 ));
           } else
           {
               $str = str_repeat( $pad_string, $length ) . $input;
           }
       } else
       {
           $str = $input;
       }

       return $str;
   }
zubfatal <root at it dot dk>
27-Mar-2005 11:28
<?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;
       }
   }

?>
Tomek Krzeminski
03-Feb-2005 03:20
for those who want to pad strings in UTF-8 charset (for example)
(orig by bob)
---------------
   private function iconv_str_pad( $input, $pad_length, $pad_string = '', $pad_type = 1, $charset = "UTF-8" )
   {
       $str = '';
       $length = $pad_length - iconv_strlen( $input, $charset );
      
       if( $length > 0)
       {
           if( $pad_type == STR_PAD_RIGHT )
           {
               $str = $input . str_repeat( $pad_string, $length );
           } elseif( $pad_type == STR_PAD_LEFT )
           {
               $str = str_repeat( $pad_string, $length ) . $input;
           } elseif( $pad_type == STR_PAD_BOTH )
           {
               $str = str_repeat( $pad_string, floor( $length / 2 ));
               $str .= $input;
               $str .= str_repeat( $pad_string, ceil( $length / 2 ));
           } else
           {
               $str = str_repeat( $pad_string, $length ) . $input;
           }
       } else
       {
           $str = $input;
       }
      
       return $str;
   }
02-Nov-2004 07:15
I just looked at bob[at]bobarmadillo[dot]coms version of str_pad and notice that he dint take into account the length of the padded string. He's assumed this is a single character, which the examples show it to be a string of characters.
giorgio dot balestrieri at mail dot wind dot it
16-Sep-2004 04:06
str_pad vs. sprintf 2nd round :)

After to have seen Rex and Squeegee results, I've ran the code again, using different OSs and PHP version.
Here my results:

OpenBSD & PHP 4.3.4

str_pad test started, please wait...
str_pad cycle completed in 88 seconds
sprintf test started, please wait...
sprintf cycle completed in 69 seconds

Windows XP & PHP 5.0.0

str_pad test started, please wait...
str_pad cycle completed in 33 seconds
sprintf test started, please wait...
sprintf cycle completed in 27 seconds

RedHat Linux 7.3 & PHP 4.3.3

str_pad test started, please wait...
str_pad cycle completed in 63 seconds
sprintf test started, please wait...
sprintf cycle completed in 43 seconds

sprintf seem to be faster yet, but considering Rex and Squeegee test, this cannot be considered always true... somebody want try more? Only to understand why... :)
tacomage at NOSPAM dot devilishly-deviant dot net
07-Jul-2004 10:04
If you want to pad a string to a certain screen length with &nbsp; or other HTML entities, but don't want to risk messing up any HTML characters inside the string, try this:

<?
function str_pad_as_single($input, $len, $pad, $flag=STR_PAD_RIGHT)
{
 
$trans=array('$'=>$input,' '=>$pad);
 
$output=str_pad('$',$len-strlen($input)+1,' ',$flag);
 
$output=strtr($output,$trans);
  return
$output;
}
echo
str_pad_as_single('<img src="some.gif">',22,'&nbsp;');
// will output <img src="some.gif">&nbsp;&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_BOTH);
// will output &nbsp;<img src="some.gif">&nbsp;

echo str_pad_as_single('<img src="some.gif">',22,'&nbsp;',STR_PAD_LEFT);
// will output &nbsp;&nbsp;<img src="some.gif">
?>

It works by using single characters for str_pad, then replacing the characters with the full strings using strtr, so the two strings can't interfere with each other.  It also conveniently has the same syntax as str_pad.  Yes, I realize that spacing an image with text isn't the best idea, but it's just an example, it'll apply to other HTML as well :-P
giorgio dot balestrieri at mail dot wind dot it
09-Mar-2004 10:49
For number formatting (like writing numbers with leading zeroes etc.) , sprintf is much faster than str_pad.
Consider the following snippet (it take some minutes to run):

<?
 
echo "str_pad test started, please wait...\n";
 
 
$intStart = time();
  for (
$idx = 1; $idx <= 10000000; $idx++)
  
$strFoo = str_pad($idx, 10, "0", STR_PAD_LEFT);
 
$intEnd = time();
 
  echo
"str_pad cycle completed in " . ($intEnd - $intStart) . " seconds\n";
  echo
"sprintf test started, please wait...\n"
 
 
$intStart = time();
  for (
$idx = 1; $idx <= 10000000; $idx++)
  
$strFoo = sprintf("%010d", $idx);
 
$intEnd = time();
 
  echo
"sprintf cycle completed in " . ($intEnd - $intStart) . " seconds\n";
?>

The str_pad cyle runs 80-100% slower on my pc...
anon at example dot com
30-May-2003 12:50
alternatively use substr_replace to zero pad:

   $new_id = substr_replace("00000", $id, -1 * strlen($id));
ed at bigoakpictures dot com
07-May-2003 05:25
Combining it into a handy one liner could be:

$string = str_replace(" ", "&nbsp;", str_pad($string, 10, " ", STR_PAD_BOTH));
tharkos at telefonica dot net
02-Apr-2003 11:24
I think the simply way to print the special HTML character &nbsp; as string is usin the conversion types.

La manera más simple de utilizar el caracter especial de HTML &nbsp; como un string es usando la comversión de tipos

echo str_repeat("&nbsp".chr(59), 10)
bob [at] bobarmadillo [dot] com
03-Dec-2002 11:22
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";
?>
david dot rensonnet at swing dot be
02-Dec-2002 05:18
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
Fahad dot Gilani at anu dot edu dot au
02-Dec-2002 04:22
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
no dot spam at no dot spam dot no
26-Sep-2002 06:28
there could already be spaces in the string.

1) strlen the string
2) replace spaces with "AUniqueString"
3) strlen the new string
4) compare the two strlen's
5) pad as needed considering the new strlen
6) finally, replace all "AUniqueString" 's with &nbsp; 's

hack & a half, slow as well i bet
cd579 at hotmail dot com
22-Aug-2002 03:53
Why not just use a space[' '] instead of a character that COULD be inside the string, and risk messing it up?  Example:

$string = 'test';

$string = str_pad($string, 10, " ", STR_PAD_BOTH);
// $string now equals '      test'

$string = str_replace(" ", "&nbsp;", $string);
mreilly at NOSPAM dot mac dot com
20-Aug-2002 01:23
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;.
saveloywill at netscape dot net
10-Aug-2002 02:50
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.
pozytron#mac#com
08-Jul-2002 04:20
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;&
cj at NOSPAM dot ceejayoz dot com
17-Jun-2002 02:38
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)
pestilenc at hotmail dot com
06-Jun-2002 06:26
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);
no_email at php dot net
30-May-2002 12:34
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.
jared at dctkc dot com
03-May-2002 06:25
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));
matthew dot somerville at trinity dot oxford dot ac dot uk
05-Aug-2001 08:53
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.
rob at OhReally dot com
03-Mar-2001 05:34
To reformat the date "3-3-2001" to "2001-03-03" you would use this regexp:

$newdate = preg_replace("/([0-9]+)-([0-9]+)-([0-9]+)/ie", "'\\3-'.str_pad('\\2', 2, '0', STR_PAD_LEFT).'-'.str_pad('\\1', 2, '0', STR_PAD_LEFT)", $date);

<str_ireplacestr_repeat>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT