str_pad – PHP String Functions
Syntax :
Description :
str_pad() function will pad a string to a certain length with another string.
Parameter :
- string – This is a Required parameter. It is the input string on which function will be performed.
- length – This is a Required parameter. It sets value of new length of a input string parameter. if the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input will be returned.
- pad_string – This is a Required parameter. It sets string to be padded with input string. Default padded string is whitespace.
- pad_type – This is an Optional parameter. It can be Specifies what side to pad the string.
- STR_PAD_RIGHT – Padding is done to the right side of the string. This is default value.
- STR_PAD_LEFT – Padding is done to the left side of the string
- STR_PAD_BOTH – Padding is done to both sides of the string. If not an even number, the right side gets the extra padding.
Output :
This will return a padded string.
Related articles : str_repeat().
str_pad() – PHP Functions Example 1 :
<?php $strExample = "Hi from tutorialmines."; echo str_pad($strExample,30,"!"); ?>
In above example ,We have a string “Hi from tutorialmines.”. Now this function will pad the string “!” in the right side of string and makes its length to 30. Output of above code in the browser is as below:
str_pad() – PHP Functions Example 2 : Padding string “!” on LEFT side of string.
<?php $strExample = "Hi from tutorialmines."; echo str_pad($strExample,30,"!",STR_PAD_LEFT); ?>
In above example ,We have a string “Hi from tutorialmines.”. Now this function will pad the string “!” in the LEFT side of string and makes its length to 30. Output of above code in the browser is as below:
str_pad() – PHP Functions Example 3 : Padding string “!” on BOTH side of string.
<?php $strExample = "Hi from tutorialmines."; echo str_pad($strExample,30,"!",STR_PAD_BOTH); ?>
In above example ,We have a string “Hi from tutorialmines.”. Now this function will pad the string “!” in the LEFT and RIGHT both side of string and makes its length to 30. Output of above code in the browser is as below:
!!!!Hi from tutorialmines.!!!!
str_pad() – PHP Functions Example 4 : length value is less than string length.
<?php $strExample = "Hi from tutorialmines."; echo str_pad($strExample,20,"!"); ?>
In above example ,We have a string “Hi from tutorialmines.”. Now str_pad() length values is less than the length of input string. So, nothing will be padded and the inpu string will be returned. Output of above code in the browser is as below:
Hi from tutorialmines.