Php str padding left

What is str_pad() in PHP?

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

Overview

PHP’s str_pad() function will pad a string to a certain length using another string. The str_pad() function does this padding by adding more characters from a set of characters indicated by the second parameter passed to it.

This addition will increase the length of the string in total to the length indicated by the third parameter passed to the function as well.

Syntax

The basic syntax of the function:

 str_pad( $string, $length, $pad_string, $pad_type ); 

Parameters

  • $string : The string to be padded.
  • $length : An integer value that indicates the new length of the string after padding.

Note: The $length parameter must be greater than the initial length of the string. If it is less than or equal to the string’s length or negative, there will be no padding on the string, and the string is returned as it is. This is a required parameter.

  • $pad_string : The string used to do the padding. This parameter is optional. If it is not provided, the default value of empty string ( «» ) will be used.

Note: If the length of the $pad_string provided cannot evenly divide the required number of padding characters, then the pad_string will be truncated.

  • $pad_type : This argument is optional. When it’s not provided, the default STR_PAD_RIGHT value will be assumed. Other pad_type includes STR_PAD_LEFT and STR_PAD_BOTH .

Return value

This function returns the padded string.

Note: It is supported by PHP versions 4.0.1 and later.

Example

//the input value to be padded.
$input = "Trick";
//no padding characters, defaults to spaces
$mani = str_pad($input, 10);
echo $mani . "test" . "\n";
// check if $mani was padded, echo new length
echo strlen($mani). "\n";
// add strings to the left.
echo str_pad($input, 10, "-=", STR_PAD_LEFT)."\n";
//add strings to both sides
echo str_pad($input, 10, "_", STR_PAD_BOTH). "\n";
//no pad_type value, defaults to right padding
echo str_pad($input, 6, "___"). "\n";
/*the pad_string length is less
than the $input string length
so no padding was done*/
echo str_pad($input, 3, "*"). "\n";
?>

Explanation

In the code example above, the variable $trick1 is padded with different str_pad() options, producing different outputs.

Example

The default pad_type is STR_PAD_RIGHT , the required number of padding characters can’t be evenly divided when using STR_PAD_BOTH . So the padding to the right will be favored over padding to the left.

Let’s see this with a simple code example:

Источник

PHP str_pad() Function

Pad to the right side of the string, to a new length of 20 characters:

Definition and Usage

The str_pad() function pads a string to a new length.

Syntax

Parameter Values

Parameter Description
string Required. Specifies the string to pad
length Required. Specifies the new string length. If this value is less than the original length of the string, nothing will be done
pad_string Optional. Specifies the string to use for padding. Default is whitespace
pad_type Optional. Specifies what side to pad the string.
  • 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 of the string
  • STR_PAD_RIGHT — Pad to the right side of the string. This is default

Technical Details

More Examples

Example

Pad to the left side of the string:

Example

Pad to both sides of the string:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Padding PHP Strings with str_pad()

In Trimming PHP Strings you learned how to remove unwanted whitespace characters from around a string. The opposite of trimming is — adding extra characters to either end (or both ends) of a string to make the string a certain length.

Padding is handy for lining up strings vertically for display, for adding leading zeroes to numbers, or for any situation where you need a string to be of a certain fixed length.

In this article you’ll explore PHP’s str_pad() function for padding strings.

Another way to pad strings is to use PHP’s printf() and sprintf() functions.

Basic str_pad() usage

In its basic form, you pass 2 arguments to str_pad() : the string to pad, and how long you want the string to be after it’s been padded. str_pad() then returns the string padded with spaces on the right-hand side. For example:

 $myString = "Hello there"; // Displays "|Hello there |" echo '|' . str_pad( $myString, 20 ) . '|'; 

If you specify a final length that’s shorter than the string to pad then the string is untouched:

 $myString = "Hello there"; // Displays "|Hello there|" echo '|' . str_pad( $myString, 5 ) . '|'; 

Padding with characters other than spaces

If you want to pad using another character, pass that character as the 3rd argument to str_pad() :

 $myString = "Hello there"; // Displays "|Hello there#########|" echo '|' . str_pad( $myString, 20, '#' ) . '|'; 

You can even pass a string of characters to use as padding. str_pad() will repeat and/or truncate the string as necessary:

 $myString = "Hello there"; // Displays "|Hello there123412341|" echo '|' . str_pad( $myString, 20, '1234' ) . '|'; 

Padding on the left

To pad the string on the left instead of on the right, pass the flag STR_PAD_LEFT as the 4th argument to str_pad() . (The default value for this flag is STR_PAD_RIGHT .) For example:

 $myString = "Hello there"; // Displays "| Hello there|" echo '|' . str_pad( $myString, 20, ' ', STR_PAD_LEFT ) . '|'; 

Padding on both sides

You can also pad a string on both sides by passing the flag STR_PAD_BOTH as the 4th argument. str_pad() attempts to add padding as evenly as possible to both sides of the string:

 $myString = "Hello there"; // Displays "| Hello there |" echo '|' . str_pad( $myString, 20, ' ', STR_PAD_BOTH ) . '|'; 

You’ve now looked at how to use PHP’s str_pad() function to add padding to a string. You’ve seen how to use custom padding characters, and how to pad a string on the left, on the right, or on both sides.

Reader Interactions

Comments

Leave a Reply Cancel reply

To include a block of code in your comment, surround it with

.

tags. You can include smaller code snippets inside some normal text by surrounding them with . tags.

Allowed tags in comments: .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Recent Posts

Источник

Padding Strings

Pad a string on the left, on the right, or on both the left and the right using str_pad() and printf() functions.

Using str_pad() function

str_pad function pad a string to a certain length with another string. This function accepts four parameters:

  1. input: The input string.
  2. length: No padding takes place if the length is negative, less than or equal to the input.
  3. pad_string: The output pad with the pattern specified by pad_string. If this parameter is not defined, the result will be padded with spaces.
  4. pad_type:
    • STR_PAD_RIGHT pad the string on the right (the default setting)
    • STR_PAD_LEFT pad the string on the left
    • STR_PAD_BOTH pad the string on both the left and the right, centering the result.

The following str_pad() basic example adds spaces to the end of the string:

By setting the optional argument pad_string , a string pattern is added at the end of the result:

By default, padding is added to the end of the string. By setting the optional argument pad_type to STR_PAD_LEFT or to STR_PAD_BOTH , the padding is added to the beginning of the string or to both ends.

'; //PHP-=-=-=-=-=-= echo str_pad("PHP", 15, '-=', STR_PAD_LEFT) .'
'; //-=-=-=-=-=-=PHP echo str_pad("PHP", 15, '-=', STR_PAD_BOTH); //-=-=-=PHP-=-=-=

The following example shows how str_pad( ) can create a justified index (or a table of contents):

'; echo str_pad('Table of Contents', 50, ' ', STR_PAD_BOTH) . "\n"; echo str_pad('Topic', 30, ' '); echo str_pad('Page #', 20, ' ', STR_PAD_LEFT) . "\n"; echo str_pad('Heading 1', 30, '.'); echo str_pad('1', 20, '.', STR_PAD_LEFT) . "\n"; echo str_pad('Heading 2', 30, '.'); echo str_pad('5', 20, '.', STR_PAD_LEFT) . "\n"; echo str_pad('Heading 3', 30, '.'); echo str_pad('11', 20, '.', STR_PAD_LEFT) . "\n"; echo str_pad('Last Heading', 30, '.'); echo str_pad('102', 20, '.', STR_PAD_LEFT) . "\n"; echo '

‘;

Table of Contents Topic Page # Heading 1. 1 Heading 2. 5 Heading 3. 11 Last Heading. 102

String padding using printf()

You can use the formatted string functions to pad the output by leading characters. In the following example, we use printf() function to pad the output with spaces and dots:

'; printf('% 35s', "Table of Contents\n"); printf("%-'.30s%'.20s", 'Topic', "Page #\n"); printf("%-'.30s%'.20s", 'Heading 1', "1\n"); printf("%-'.30s%'.20s", 'Heading 2', "5\n"); printf("%-'.30s%'.20s", 'Heading 3', "11\n"); printf("%-'.30s%'.20s", 'Last Heading', "101\n"); echo '

‘;

Table of Contents Topic. Page # Heading 1. 1 Heading 2. 5 Heading 3. 11 Last Heading. 101

Working with Strings:

Источник

Читайте также:  Java как дождаться окончания потока
Оцените статью