How to Use PHP's str_pad Function for String Padding
This article explains PHP's built‑in str_pad function, detailing its syntax, parameters, and usage examples for right, left, and both‑side string padding, helping developers format strings to a desired length in backend applications.
When writing PHP code, you often need to manipulate strings, and sometimes you need to pad a string to a specific length. The built‑in str_pad function can accomplish this by adding a specified string to the left or right side of the original string until the desired length is reached.
Basic Syntax:
<code>string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )</code>The parameters are:
$input : the string to be padded.
$pad_length : the length of the resulting string after padding.
$pad_string : the string used for padding (default is a space).
$pad_type : specifies the direction of padding (right, left, or both).
Usage Examples
Below are several examples demonstrating how to use the str_pad function:
1. Pad a string on the right side:
<code>$input = "Hello";
$pad_length = 10;
$pad_string = "World";
$pad_type = STR_PAD_RIGHT;
$result = str_pad($input, $pad_length, $pad_string, $pad_type);
// Output: "HelloWorld"
</code>In this example, the original string "Hello" (length 5) is padded on the right with "World" until the total length reaches 10.
2. Pad a string on the left side:
<code>$input = "Hello";
$pad_length = 10;
$pad_string = "World";
$pad_type = STR_PAD_LEFT;
$result = str_pad($input, $pad_length, $pad_string, $pad_type);
// Output: "WorldHello"
</code>Here, the string "Hello" is padded on the left with "World" to reach the length of 10.
3. Pad a string on both sides:
<code>$input = "Hello";
$pad_length = 9;
$pad_string = "World";
$pad_type = STR_PAD_BOTH;
$result = str_pad($input, $pad_length, $pad_string, $pad_type);
// Output: "WorldHelloWorld"
</code>In this case, the string "Hello" is padded evenly on both sides with "World" until the total length becomes 9.
The str_pad function is useful for various string‑processing scenarios, allowing flexible control over padding length and content by adjusting the pad_length and pad_string parameters.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.