PHP str_pad() Function
In this chapter you will learn:
- Definition for PHP str_pad() Function
- Syntax for PHP str_pad() Function
- Parameter for PHP str_pad() Function
- Return for PHP str_pad() Function
- Example - Padding on both side
- Example - Padding with specified character
- Example - Set which side to pad
Definition
The str_pad()
function makes a given input larger by length.
Syntax
PHP str_pad() Function has the following syntax.
string str_pad ( string input, int length [, string padding [, int type]] )
Parameter
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:
- STR_PAD_BOTH - Pad to both sides of the string. If not an even number, the right side gets the extra padding
- STR_PAD_LEFT - Pad to the left side
- STR_PAD_RIGHT - Pad to the right side. This is default
Return
PHP str_pad() function returns the padded string.
Example 1
Padding on both side
<?PHP/*j a v a 2s. co m*/
$string = " java2s.com ";
$newstring = str_pad($string, 30);
print ">"+$newstring+"<";
?>
The code above generates the following result.
Example 2
An optional third parameter sets the padding character to use, so:
<?PHP/*from j a va2 s. c om*/
$string = " java2s.com!";
$newstring = str_pad($string, 20, 'a');
print $newstring;
?>
The code above generates the following result.
Example 3
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//from j a v a2s . 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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP str_repeat() Function
- Syntax for PHP str_repeat() Function
- Parameter for PHP str_repeat() Function
- Return for PHP str_repeat() Function
- Example - Repeat the string 3 times