Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill the remainder of a string with blank spaces

Tags:

php

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.
like image 339
user1499315 Avatar asked Jul 19 '12 09:07

user1499315


1 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 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.

like image 90
bardiir Avatar answered Sep 23 '22 14:09

bardiir