Clear definition for the PHP str_pad() Function

前端 未结 2 438
借酒劲吻你
借酒劲吻你 2021-01-26 02:49

what is the effect of the function str_pad() to strings? please explain to me because I cant understand its definition from w3schools. Thanks.

相关标签:
2条回答
  • 2021-01-26 03:18
    string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]])
    

    Next up, str_pad() makes a given string (parameter one) larger by X number of characters (parameter two) by adding on spaces. For example:

    <?php
        $string = "Goodbye, Perl!";
        $newstring = str_pad($string, 10);
    ?>
    

    That code would leave " Goodbye, Perl! " in $newstring, which is the same string from $string except with five spaces on either side, equalling the 10 we passed in as parameter two.

    Str_pad() has an optional third parameter that lets you set the padding character to use, so:

    <?php
        $string = "Goodbye, Perl!";>
        $newstring = str_pad($string, 10, 'a');
    ?>
    

    That would put "aaaaaGoodbye, Perl!aaaaa" into $newstring.

    We can extend the function even more by using it is optional fourth parameter, which allows us to specify which side we want the padding added to. The fourth parameter is specified as a constant, and you either use STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH:

    <?php
        $string = "Goodbye, Perl!";
        $a = str_pad($string, 10, '-', STR_PAD_LEFT);
        $b = str_pad($string, 10, '-', STR_PAD_RIGHT);
        $c = str_pad($string, 10, '-', STR_PAD_BOTH);
    ?>
    

    That code will set $a to be "----------Goodbye, Perl!", $b to be "Goodbye, Perl!----------", and $c to be "-----Goodbye, Perl!-----", as expected.

    Note that HTML only allows a maximum of one space at any time. If you want to pad more, you will need to use " ", the HTML code for non-breaking space.

    0 讨论(0)
  • 2021-01-26 03:22

    It pads a string to a certain length with (optional) another string.

    For example

    $foo = 'hello world'; // length 11
    echo str_pad($foo, 13); // will echo 'hello world  ';
    

    You can also add a string for padding

    $foo = 'hello world';
    echo str_pad($foo, 13, 'x'); // will echo 'hello worldxx';
    

    Moreover you can specify where you want the string to be padded

    $foo = 'hello world';
    echo str_pad($foo, 13, 'x', STR_PAD_LEFT); // will echo 'xxhello world';
    
    $foo = 'hello world';
    echo str_pad($foo, 15, 'x', STR_PAD_BOTH); // will echo 'xxhello world';
    

    However, never use w3schools for PHP but try to understand it directly from PHP documentation

    0 讨论(0)
提交回复
热议问题