How do I make sure a string is a certain length?
To do this, you use the str_pad function, which works by ensuring that the string is padded to the length of pad_length with another string.
If that all seems a bit obscure, here is an example of how we can use str_pad to pad out the length of a certain string.
<?php
$str = "I feel like I'm floating in";
echo "<" . str_pad($str,40) . ">";
//<I feel like I'm floating in >
?>
You can see from the closing angle bracket that this has been spadded with space - the default pad if nothing is specified, but let's say that we want to specify something to pad it with, well here we go:
<?php
$str = "I feel like I'm floating in ";
echo "<" . str_pad($str,43,"space") . ">";
//<I feel like I'm floating in spacespacespace>
?>
As you can see, this function is extremely useful when you want to pad a string, which is quite a common requirement when processing, storing and perhaps particularly when displaying data.
Comment on this Question and Answer >>>
ASK A QUESTION
More strings PHP Questions
How do I make the first letter of each word upper case?What is the usage of {} in strings?
How do I print text to the screen?
How do we count paragraphs or newlines?
How do I count how many times each character occurs in a string?
