PHP Doku:: Erweitert einen String unter Verwendung eines anderen Strings auf eine bestimmte Länge - function.str-pad.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenstr_pad

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<str_ireplace

str_repeat>>

str_pad

(PHP 4 >= 4.0.1, PHP 5)

str_padErweitert einen String unter Verwendung eines anderen Strings auf eine bestimmte Länge

Beschreibung

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

Die Funktion gibt den input-String, erweitert auf der linken, rechten oder auf beiden Seiten um die angegebene Länge, zurück. Wenn das optionale Argument pad_string nicht angegeben ist, wird input durch Leerzeichen erweitert, anderenfalls bis zum Ende durch die in pad_string angegebenen Zeichen.

Parameter-Liste

input

Die Eingabezeichenkette.

pad_length

Wenn der Wert von pad_length negativ, kürzer als oder gleich der Länge der Eingabezeichenkette ist, wird keine Erweiterung durchgeführt.

pad_string

Hinweis:

pad_string wird abgeschnitten, falls die benötigte Anzahl der zu ergänzenden Zeichen nicht gleichmäßig durch die Länge von pad_string geteilt werden kann.

pad_type

Das optionale Argument pad_type kann STR_PAD_RIGHT, STR_PAD_LEFT oder STR_PAD_BOTH sein. Wird pad_type nicht angegeben, so wird standardmäßig von STR_PAD_RIGHT ausgegangen.

Rückgabewerte

Gibt die erweiterte Zeichenkette zurück.

Beispiele

Beispiel #1 str_pad()-Beispiel

<?php
$input 
"Alien";
echo 
str_pad($input10);                      // ergibt "Alien     "
echo str_pad($input10"-="STR_PAD_LEFT);  // ergibt "-=-=-Alien"
echo str_pad($input10"_"STR_PAD_BOTH);   // ergibt "__Alien___"
echo str_pad($input"___");               // ergibt "Alien_"
?>


43 BenutzerBeiträge:
- Beiträge aktualisieren...
Vasu Adiga
24.09.2010 13:31
Modifying Kari's code (see below) for UTF-8 string padding:

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
   
$diff = strlen($input) - mb_strlen($input, 'UTF-8');
    return
str_pad($input, $pad_length+$diff, $pad_string, $pad_type);
}
?>
goellerk at bucks dot edu
7.06.2010 21:43
Apparently, as of 5.3.2 the notations "STR_PAD_LEFT" and "STR_PAD_RIGHT" are case sensitive.

$yr = "10";
$yr = str_pad($yr,2,'0',str_pad_left);
print "yr = '$yr'";
yr = '  '

$yr = "10";
$yr = str_pad($yr,2,'0',STR_PAD_LEFT);
print "yr = '$yr'";
yr = '10'
shelby at coolpage dot com
19.11.2009 18:52
Convenience functions (perhaps these should be added as native functions if popular?):

<?php
function str_lpad( &$s, &$l, &$p = ' ' ) { return str_pad( $s, $l, $p, STR_PAD_LEFT ); }
function
str_nlpad( &$s, &$l ) { return str_lpad( $s, $l, '0' ); }
function
str_npad( &$s, &$l ) { return str_pad( $s, $l, '0' ); }
?>

E.g.:

<?php
$mystr
= str_nlpad( $mystr, 4 )
?>

Are more concise, semantically coherent, and perhaps also more efficient because do not create an intermediate discarded string, than the clever:

http://www.php.net/manual/en/function.str-pad.php#14585
<?php
$mystr
= substr("0000$mystr",-4)
?>
hernanc
24.04.2009 17:45
To get Monday and Sunday's dates of the current week in Y-m-d format  do:

<?php
$mon_date
= date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT) .'1'));
$sun_date date('Y-m-d',strtotime(date('Y') . 'W' . str_pad(date('W'), 2, '0',STR_PAD_LEFT).'7'));
?>
Kari "Haprog" Sderholm
21.03.2009 15:43
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);
}
?>
matrebatre
16.10.2008 20:28
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.
zarel at aesoft dot org
29.09.2008 20:35
A smaller pad_between_strings:

<?php
function pad_between_strings($string1, $string2, $length, $char = ' ') {
    return
str_pad($string1, $length-strlen($string2), $char) . $string2;
}
?>
warmo_at_o2_dot_pl
27.08.2008 13:56
@albert dot serra at camaleongroup dot com
You are reinventing the wheel, and your wheel isn't even round. PHP has built-in functions which will accomplish this task and they are called rtrim and ltrim. Look at code below:
<pre>
<?php
  $string
= 'HOME*******';
  echo
rtrim($string, '*')."\n"// HOME

 
$string = '*****HOME';
  echo
ltrim($string, '*')."\n"; // HOME

 
$string = '*****HOME*****';
  echo
trim($string, '*')."\n"; // HOME
?>
</pre>
albert dot serra at camaleongroup dot com
22.07.2008 15:36
<?php
/** Description
   * padclear, clear a pad varchar(9) "*****HOME" -> varchar(4) "HOME"
   * _no use for INT_ : varchar(5) "00100" -> int(3) "100", use $number = (int) "00100";
   *
   * @param string, string original
   * @param char, character to replace
   * @param charreplace, final character
   * @param type, [STR_PAD_RIGHT|STR_PAD_LEFT] see str_pad
   * @return string, transformed string with charreplace
   */
 
function padclear($string, $char, $charreplace = null,$type = STR_PAD_RIGHT) {

     
$strlen = strlen($string) - 1;
     
$i = ($type == STR_PAD_RIGHT) ? 0 : $strlen;
     
$stop = ($type == STR_PAD_RIGHT) ? $strlen : 0;
     
$difpos = null;
      while(
is_null($difpos) && $i != $stop) {
       
$difpos = ($string[$i] != $char) ? $i : null;
        if(
$type == STR_PAD_RIGHT) $i++;
        else
$i--;
      }

      if(
$type == STR_PAD_RIGHT) {
       
$ant = str_replace($char,$charreplace,substr($string,0,$difpos));
        
$nxt = substr($string,$difpos,$strlen);
      } else {
       
$ant = substr($string,0,$difpos);
       
$nxt = str_replace($char,$charreplace,substr($string,$difpos,$strlen));
      }

      return
$ant . $nxt;
  }

 
$string = "HOME*******";
  echo
padclear($string,'*','',STR_PAD_LEFT);  // HOME
 
$string = "*****HOME";
  echo
padclear($string,'*','',STR_PAD_RIGHT); // HOME
?>
bxi at apparoat dot nl
20.03.2008 15:17
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;
}
?>
Spudley
18.07.2007 17:47
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.
christian dot reinecke at web dot de
1.04.2007 19:43
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.
Charles
6.12.2006 0:53
More corrections to the original flap / Tomek Krzeminski code below (well someone has to check it!) -- the code is a bit mangled but it is still the same:

<?php

function mb_str_pad($ps_input, $pn_pad_length, $ps_pad_string = " ", $pn_pad_type = STR_PAD_RIGHT, $ps_encoding = NULL) {
 
$ret = "";

  if (
is_null($ps_encoding))
   
$ps_encoding = mb_internal_encoding();

 
$hn_length_of_padding = $pn_pad_length - mb_strlen($ps_input, $ps_encoding);
 
$hn_psLength = mb_strlen($ps_pad_string, $ps_encoding); // pad string length
  
 
if ($hn_psLength <= 0 || $hn_length_of_padding <= 0) {
   
// Padding string equal to 0:
    //
   
$ret = $ps_input;
    }
  else {
   
$hn_repeatCount = floor($hn_length_of_padding / $hn_psLength); // how many times repeat

   
if ($pn_pad_type == STR_PAD_BOTH) {
     
$hs_lastStrLeft = "";
     
$hs_lastStrRight = "";
     
$hn_repeatCountLeft = $hn_repeatCountRight = ($hn_repeatCount - $hn_repeatCount % 2) / 2;

     
$hs_lastStrLength = $hn_length_of_padding - 2 * $hn_repeatCountLeft * $hn_psLength; // the rest length to pad
     
$hs_lastStrLeftLength = $hs_lastStrRightLength = floor($hs_lastStrLength / 2);      // the rest length divide to 2 parts
     
$hs_lastStrRightLength += $hs_lastStrLength % 2; // the last char add to right side

     
$hs_lastStrLeft = mb_substr($ps_pad_string, 0, $hs_lastStrLeftLength, $ps_encoding);
     
$hs_lastStrRight = mb_substr($ps_pad_string, 0, $hs_lastStrRightLength, $ps_encoding);

     
$ret = str_repeat($ps_pad_string, $hn_repeatCountLeft) . $hs_lastStrLeft;
     
$ret .= $ps_input;
     
$ret .= str_repeat($ps_pad_string, $hn_repeatCountRight) . $hs_lastStrRight;
      }
    else {
     
$hs_lastStr = mb_substr($ps_pad_string, 0, $hn_length_of_padding % $hn_psLength, $ps_encoding); // last part of pad string

     
if ($pn_pad_type == STR_PAD_LEFT)
       
$ret = str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr . $ps_input;
      else
       
$ret = $ps_input . str_repeat($ps_pad_string, $hn_repeatCount) . $hs_lastStr;
      }
    }

  return
$ret;
  }

?>
flap
26.09.2006 10:59
here is some extension to Tomek Krzeminski example. It works correctly when length of pad_string is greater than 1
(orig by Tomek Krzeminski)

function m_str_pad($input, $pad_length, $pad_string = '', $pad_type = 1, $charset = null){
    $str = '';
      
    if ($charset==null)
        $charset = mb_internal_encoding();
      
    $length = $pad_length - mb_strlen($input, $charset);
   
    $psLength = mb_strlen($pad_string); // pad string length
   
    if ($psLength<=0 OR $length<=0){
        // pad string equal 0
        $str = $input;
    }else{
        // pad string AND space to padding is greater than 1
        $repeatCount = floor($length/$psLength); // how many times repeat
        $lastStr = substr($pad_string, 0, $length%$psLength); // last part of pad string
       
        if($pad_type == STR_PAD_RIGHT){
            $str = $input.str_repeat($pad_string, $repeatCount).$lastStr;
        } elseif($pad_type == STR_PAD_LEFT){
            $str = str_repeat($pad_string, $repeatCount).$lastStr.$input;
        } elseif($pad_type == STR_PAD_BOTH){
            $repeatCountLeft = 0;
            $repeatCountRight = 0;
            $lastStrLeft = '';
            $lastStrRight = '';
           
            if ($repeatCount%2==0){
                // if is divisible 2
                $repeatCountLeft = $repeatCountRight = floor($repeatCount/2);
            }else{
                // if not - has to dive to 2 same parts
                $repeatCountLeft = $repeatCountRight = floor(($repeatCount-1)/2);
            }
           
            $lastStrLength = $length-2*$repeatCountLeft*$psLength; // the rest length to pad
            $lastStrLeftLength = $lastStrRightLength = floor($lastStrLength/2); // ther rest length divide to 2 parts
            $lastStrRightLength += $lastStrLength%2; // the last char add to right side
           
            $lastStrLeft = substr($pad_string, 0, $lastStrLeftLength);
            $lastStrRight = substr($pad_string, 0, $lastStrRightLength);
           
            $str  = str_repeat($pad_string,$repeatCountLeft).$lastStrLeft;
            $str .= $input;
            $str .= str_repeat($pad_string,$repeatCountRight).$lastStrRight;
        } else{
            $str = str_repeat($pad_string, $repeatCount).$lastStr.$input;
        }
    }
     
    return $str;
}
rafaeljaquestudojunto at gmail dot com
11.09.2006 14:43
Looking forward to make some dynamic tabulation, i've noticed that the output appeared twice. I suppose that the parser recognize \t, \n and any other special character as a single character...

So.. If you need 4 tabulatins, just make...

<?php

print str_pad('',4,"\t");

?>
Silvio Ginter (silvio dot ginter at gmx dot de)
15.11.2005 17:43
Hello,

i updated the function in my last post. it should be much more performant now.

<?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);
}
?>
Silvio Ginter (silvio dot ginter at gmx dot de)
15.11.2005 16:53
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, 100, '#', $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) {
   
$dir = 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:
               
/* reduce on both sides, beginning with the right one. */
               
while (strlen($str) > $len) {
                    if (
$dir == STR_PAD_RIGHT) {
                       
$str = substr($str, 0, (strlen($str) - 1));
                       
$dir = STR_PAD_LEFT;
                    }
                    else {
                       
$str = substr($str, 1);
                       
$dir = STR_PAD_RIGHT;
                    }
                }
                break;
            default:
               
$str = substr($str, 0, $len);
                break;
        }
    }
    return (
$len - $origLen);
}
?>
Michal Nazarewicz, min86 at tlen dot pl
24.09.2005 12:27
Re ks:
Your function does something different if $padchar is not a chararcter but rather a string. Still, however, private's function may be simplified:

<?php
function str_pad_right($str, $pad, $len) {
    return
$str . str_pad('', $len, $pad);
}
function
str_pad_left($str, $pad, $len) {
    return
str_pad('', $len, $pad) . $str;
}
function
str_pad_both($str, $pad, $len) {
    return (
$s = str_pad('', $len, $pad)) . $str . $s;
}
?>
ks
11.08.2005 21:57
in reply to private dot email at optusnet dot com dot au:

you are defying the point of padding by adding a fixed amount of characters!

anyways, your functions are equivalent to the much simpler form of e.g.:

<?php

function str_pad_right($string, $padchar, $int) {
   return
$str . str_repeat($padchar, $int);
}

?>
private dot email at optusnet dot com dot au
10.08.2005 14:04
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!
Anloc
19.05.2005 18: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
28.03.2005 7: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
3.02.2005 10: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;
    }

2.11.2004 14: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.09.2004 23: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
8.07.2004 5: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
9.03.2004 17: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.05.2003 19:50
alternatively use substr_replace to zero pad:

    $new_id = substr_replace("00000", $id, -1 * strlen($id));
ed at bigoakpictures dot com
7.05.2003 12: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
2.04.2003 19: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
3.12.2002 18: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
2.12.2002 12: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
2.12.2002 11: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
27.09.2002 1: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.08.2002 22: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.08.2002 20: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.08.2002 21: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
8.07.2002 23: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.06.2002 21: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
6.06.2002 13: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.05.2002 19: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
4.05.2002 1: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
5.08.2001 15: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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)