PHP/String/str pad

Материал из Web эксперт
Перейти к: навигация, поиск

Make use of str_pad()"s optional parameters

   <source lang="html4strict">

<? $header = "Table of Contents"; print str_pad ($header, 5, "=-", STR_PAD_BOTH); ?>

 </source>
   
  


string str_pad ( string input, int length [, string padding [, int type]] )

   <source lang="html4strict">

<?

   $string = "Goodbye, Perl!";
   $newstring = str_pad($string, 2);

?>

 </source>
   
  


str_pad-2.php

   <source lang="html4strict">

<?php

  $header = "Log";
  echo str_pad ($header, 20, "=+", STR_PAD_BOTH);

?>

 </source>
   
  


str_pad() function pads string to length pad_length with a specified characters

   <source lang="html4strict">

Its syntax is: string str_pad (string input, int pad_length [, string pad_string [, int pad_type]]) If pad_string is not specified, string will be padded with blank spaces. pad_type may be assigned STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH This example shows how to pad a string using str_pad() defaults: <? $food = "salad"; print str_pad ($food, 5); ?>

 </source>
   
  


STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH:

   <source lang="html4strict">

<?

   $string = "Goodbye, Perl!";
   $a = str_pad($string, 10, "-", STR_PAD_LEFT);
   $b = str_pad($string, 10, "-", STR_PAD_RIGHT);
   $c = str_pad($string, 10, "-", STR_PAD_BOTH);

?>

 </source>
   
  


str_pad.php

   <source lang="html4strict">

<?php

  echo str_pad("Salad", 10)." is good.";

?>

 </source>
   
  


There is an optional third parameter to str_pad( ) that lets you set the padding character to use

   <source lang="html4strict">

<?

   $string = "Goodbye, Perl!";
   $newstring = str_pad($string, 10, "a");

?>

 </source>
   
  


Using left space padding

   <source lang="html4strict">

<?php printf("Space padding can be tricky in HTML % 5d.", 42); ?>

 </source>
   
  


Using left zero padding

   <source lang="html4strict">

<?php printf("Zero padding can help alignment %05d.", 42); ?>

 </source>