Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 41
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Porady zamieszczone tutaj przez Darka są pomocne w wielu chwilach. Wielokrotnie tworząc jakiś złożony serwis korzystam z tych porad. Można by tworzyć samemu te skrypty, ale tak naprawdę czy nie lepiej jest wziąć skrypt z tej strony i zmodyfikowac go dla swoich potrzeb? Wprawdzie możemy taki skrypt napisać sami, ale po co, skoro stracimy czas na coś, co ktoś juz napisał, przetestował i może zagwarantować, że działa poprawnie. Któryś raz z rzędu opłacam abonament i nie raz jeszcze opłacę. Kawał dobrej roboty i ogrom wiedzy w jednym miejscu.

Piotr Karamański
Design Studio

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

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.

Przykład 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_"
?>

Notatka: 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

mike97gt at yahoo dot com
01-Dec-2005 09:04

Use str_pad to mask a credit card number.

<?
$ccnum
= $_POST['CC_Number'];
$ccmask = str_pad(substr($ccnum, -4), strlen($ccnum), 'x', STR_PAD_LEFT);
?>

Works great for storing last 4 digits of credit card number in a database.


Silvio Ginter (silvio dot ginter at gmx dot de)
15-Nov-2005 05: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-Nov-2005 04: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-Sep-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-Aug-2005 09: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-Aug-2005 02: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 <info NOSPAM at anloc dot net>
19-May-2005 06: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>
28-Mar-2005 07: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 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;
   }


02-Nov-2004 02: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 11: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
08-Jul-2004 05: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 05: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 07: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 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
02-Apr-2003 07:24

I think the simply way to print the special HTML character &nbsp; as string is usin the conversion types.

La manera m

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt