7

I have a string with, for example, 32 characters. For first, i want to establish that the string have max 32 characters and i want add blank spaces if characters is only, for example, 9.

Example:

ABCDEFGHI ---> 9 characters

I want this:

ABCDEFGHI_______________________ ---> 9 characters + 23 blank spaces added automatically.
desertnaut
  • 57,590
  • 26
  • 140
  • 166
user1499315
  • 139
  • 1
  • 1
  • 8
  • Possible duplicate of [Formatting a number with leading zeros in PHP](http://stackoverflow.com/questions/1699958/formatting-a-number-with-leading-zeros-in-php) – Organic Advocate Dec 06 '16 at 15:53

7 Answers7

8

The function you are looking for is str_pad.

http://php.net/manual/de/function.str-pad.php

$str = 'ABCDEFGHI';
$longstr = str_pad($str, 32);

The default pad string already is blank spaces.

As your maximum length should be 32 and str_pad won't take any action when the string is longer than 32 characters you might want to shorten it down using substr then:

http://de.php.net/manual/de/function.substr.php

$result = substr($longstr, 0, 32);

This again won't take any action if your string is exactly 32 characters long, so you always end up with a 32 characters string in $result now.

bardiir
  • 14,556
  • 9
  • 41
  • 66
1

Use str_pad:

str_pad('ABCDEFGHI', 32);
Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
1

Use str_pad function:

$result = str_pad($input, 32, " ");
Aleks G
  • 56,435
  • 29
  • 168
  • 265
1

you need str_pad

$padded = str_pad($in,32,' ');

You can have left or right padded, tons of options, check them all out here

If the input exceeds 32 chars, no action is taken, but that's an easy check to implement:

if (strlen($padded) > 32)
{
    throw new Exception($padded.' is too long');//or some other action
}
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
0

If you want to do more customization inside the function you could use this

function fill($input, $length, $filler = ' ')
{
    $len = strlen($input);
    $diff = $length - $len;

    if($diff > 0)
    {
        for ($i = 0; $i < $diff; $i++)
        {
            $input = $input . $filler;
        }
    }
    return substr($input, 0, $length);
}
Dion
  • 53
  • 1
  • 1
  • 7
-1
for($i=0;$i<(32-strlen($your_string));$i++)
{ 
    $new_string.=$your_string.' '
}

hope that would be helpful for you

Ron
  • 24,175
  • 8
  • 56
  • 97
guosheng1987
  • 107
  • 1
  • 7
  • very good approach, but when there are built-in methods we shouldn't try custom designed logics.. i hope you got my point.. – rummykhan Nov 15 '15 at 01:48
-4
$str = "ABCDEFGHI";
for ($i = 0; $i < 23; $i++) {
    $str .= "&nbsp;";
}

This is what You want?

When saw other comments, then that will be the best solution.

dpitkevics
  • 1,238
  • 8
  • 12