Hướng dẫn dùng python str.pad trong PHP

[PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8]

str_padPad a string to a certain length with another string

Description

str_pad[
    string $string,
    int $length,
    string $pad_string = " ",
    int $pad_type = STR_PAD_RIGHT
]: string

Parameters

string

The input string.

length

If the value of length is negative, less than, or equal to the length of the input string, no padding takes place, and string will be returned.

pad_string

Note:

The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

pad_type

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

Return Values

Returns the padded string.

Examples

Example #1 str_pad[] example

Marjune

7 years ago

since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were always favor in the right pad if the required number of padding characters can't be evenly divided.

e.g

robertwhishaw at gmail dot com

2 years ago

Incrementing or decrementing numbers in PHP is easy with the ++ and -- operators but it can be difficult to set the precision of the numbers. The str_pad[] can be useful for concatenating a string to the beginning or end of the incrementing number to simulate a different precision.

Good example, we want to increment 001 to 002, 003, 004:

$numbers = [];

for[$i = 1; $i '001',
$numbers[1] => '002',
$numbers[2] => '003',
$numbers[3] => '004',

Bad example, we want to increment 001 to 002, 003, 004 but if we set $i = 001 in the for[] loop to start with, 001 will be converted to 1 and the incrementing will return: 1, 2, 3, 4 etc...

$numbers = [];

for[$i = 001; $i 1,
$numbers[1] => 2,
$numbers[2] => 3,
$numbers[3] => 4,

wes at nospamplsexample dot org

7 years ago

multibyte version:

qeremy [atta] gmail [dotta] com

9 years ago

A proper unicode string padder;



Test;


Output;
len 3: ...
len 3: ...

len 4: ...A
len 4: ...Ä

len 5: A...A
len 5: Ä...Ä

len 6: A...AO
len 6: Ä...ÄÖ
...

pestilenc at hotmail dot com

20 years ago

For me this worked.
$string = 'help';

#First, str_pad[] with unique character.
$string = str_pad[$string, 10, "*", STR_PAD_BOTH];
#$string = '***help***';

#Second, str_replace with ' '
$string = str_replace["*", " ", $string];

mcinp

7 years ago

a different, more robust multibyte version of str_pad that works correctly only if $pad_string is non-multibyte string

function my_mb_str_pad[$input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT,$encoding='UTF-8']{
    $mb_diff=mb_strlen[$str, $encoding]-strlen[$string];       
    return str_pad[$input,$pad_length+$mb_diff,$pad_string,$pad_type];
}

bob [at] bobarmadillo [dot] com

19 years ago

In a lot of cases you're better off using str_repeat if you want to use something like   - it repeats the entire string.

Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every other way:

Spudley

15 years ago

Warning: If your string includes non-ascii characters [eg the British pounds sign], str_pad[] will treat these as two characters when calculating the padding.

So for example:

will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.

neo_selen

2 years ago

you can use str_pad to display an integer with a fixed amount of digits, like that:
0002
0003
...
0100

by just writing



i set 4 digits [see parameter #2], but you can set any fitting your needs.

gene at swipesy dot com

10 years ago

This is how I pad using   :

str_replace[" ", "  ", str_pad[$foo, 10, " ", STR_PAD_LEFT]]

Seems to work well using two   tags for each character added, at least for my use. YMMV.

Fahad dot Gilani at anu dot edu dot au

19 years ago

Basically, *all* of you guys have a 'long' way of padding text with html tags [which includes  ] You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:

Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad

Kirill Fuchs

5 years ago

sprintf[] is not always faster... It certainly scales a lot better then str_pad so when running a benchmark that pads 10k characters,  sprintf will come out on top. But if you benchmarked a more real world scenario, it seems str_pad comes out the clear winner.

$sTime = microtime[true];
$count = 5;
$s = sprintf["%'\n5s", "\n"];
$eTime = microtime[true];
echo 'sprintf ran in ' . [[$eTime - $sTime] * 1000] . ' milliseconds' . "\n";

$sTime = microtime[true];
$s = str_pad["\n", 5, "\n"];
$eTime = microtime[true];
echo 'str_pad ran in ' . [[$eTime - $sTime] * 1000] . ' milliseconds' . "\n";

sprintf ran in 0.015974044799805 milliseconds
str_pad ran in 0.0059604644775391 milliseconds

christian dot reinecke at web dot de

15 years ago

Fills the first argument [mostly a number, f.e. from a loop to display a date or time] with zeroes.



sprintf[] is indeed faster than str_pad.

gtwizard

5 years ago

sprintf is faster

$sTime = microtime[true];
$s = sprintf["%'-1000000s", '-'];
$eTime = microtime[true];
echo 'sprintf ran in ' . [[$eTime - $sTime] * 1000] . ' milliseconds' . "\n";

$sTime = microtime[true];
$s = str_pad['-', 1000000, '-'];
$eTime = microtime[true];
echo 'str_pad ran in ' . [[$eTime - $sTime] * 1000] . ' milliseconds' . "\n";

//result
sprintf ran in 2.0260810852051 milliseconds
str_pad ran in 26.59797668457 milliseconds

Anonymous

6 years ago

Here is the mcinp's version of mb_str_pad bugfixed:

Still working correctly only if $pad_string is non-multibyte string

bxi at apparoat dot nl

14 years ago

In case you want to pad 2 strings together with a character you can use:

zubfatal

17 years ago

matrebatre

13 years ago

Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432



$n indicates how many characters you want.

private dot email at optusnet dot com dot au

17 years ago

I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.



Hope this can help someone!

Kari "Haprog" Sderholm

13 years ago

Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "åäöÅÄÖ" that are double byte in UTF-8.

NOSPAM dot php at my dot jrklein dot com

2 years ago

str_pad[] can provide sufficient "zero padding" when using block ciphers and manual padding with openssl_encrypt[] and similar.

The example below will pad the 6 character text "Secret" with two \x00 characters and return 8 characters of data. Substitute your plain text and block size as needed.

Chủ Đề