Fill the rest of the line with blank spaces

Thank you for your support. I have a string with, for example, 32 characters. Firstly, I want to establish that the string has a maximum of 32 characters, and I want to add spaces, if only characters, for example, 9.

Example:

ABCDEFGHI ---> 9 characters

I want it:

ABCDEFGHI_ __________ ---> 9 characters added + 23 empty spaces.

thanks

+4
source share
8 answers

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 string already contains spaces.

Since your maximum length should be 32, and str_pad will not take any action if the string is longer than 32 characters, you can shorten it with substr , and then:

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

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

This again will take no action if your line has exactly 32 characters, so you always end up with a line with 32 characters in $result .

+5
source

Use str_pad :

 str_pad('ABCDEFGHI', 32); 
+1
source

Use the str_pad function:

 $result = str_pad($input, 32, " "); 
+1
source

you need str_pad

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

You can have left or right gasket, many options, check them all here

If the input exceeds 32 characters, no action is taken, but for a simple check:

 if (strlen($padded) > 32) { throw new Exception($padded.' is too long');//or some other action } 
+1
source

I am not a PHP developer, but I think this is what you want.

0
source
 for($i=0;$i<(32-strlen($your_string));$i++) { $new_string.=$your_string.' ' } 

hope you find it helpful

0
source

If you want to make more settings inside the function, you can 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); } 
0
source
 $str = "ABCDEFGHI"; for ($i = 0; $i < 23; $i++) { $str .= "&nbsp;"; } 

Is this what you want?

When you saw other comments, this would be the best solution.

-2
source

All Articles