The str_pad()
function makes a given input larger by length.
PHP str_pad() Function has the following syntax.
string str_pad ( string input, int length [, string padding [, int type]] )
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to pad |
length | Required. | New string length. If this value is less than the original length of the string, nothing will be done |
pad_string | Optional. | String to use for padding. Default is whitespace |
pad_type | Optional. | What side to pad the string. |
Possible values for pad_type:
PHP str_pad() function returns the padded string.
Padding on both side
<?PHP
$string = " java2s.com ";
$newstring = str_pad($string, 30);
print ">"+$newstring+"<";
?>
The code above generates the following result.
An optional third parameter sets the padding character to use, so:
<?PHP
$string = " java2s.com!";
$newstring = str_pad($string, 20, 'a');
print $newstring;
?>
The code above generates the following result.
The optional fourth parameter specifies which side
we want the padding added to.
The fourth parameter can be either STR_PAD_LEFT
,
STR_PAD_RIGHT
, or STR_PAD_BOTH
:
<?PHP/* ww w . j a va2s . co m*/
$string = " java2s.com!";
$a = str_pad($string, 20, '-', STR_PAD_LEFT);
print $a;
print "\n";
$b = str_pad($string, 20, '-', STR_PAD_RIGHT);
print $b;
print "\n";
$c = str_pad($string, 20, '-', STR_PAD_BOTH);
print $c;
?>
To pad more spaces to HTML, you will need to use the HTML code for a non-breaking space.
The code above generates the following result.