PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I make sure a string is a certain length?


If you want to make sure that your string is a certain length, then you can pad it.

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.



More strings PHP Questions

How do I print the " in an echo statement?
How do I convert newlines to HTML line break tags?
How do I convert characters to HTML entities using PHP?
How do I calculate the metaphone of a string?
How can I remove trailing space from a string?