PHP Questions Home | Register | Login
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website
Unanswered

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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.



Comment on this Question and Answer >>>

ASK A QUESTION

More strings PHP Questions

How can I repeat a string several times?

How do you hash the password in this php script: define(sb db user name, admin store); define(sb db password, mypassword);

how to compare strings in PHP?

How do I remove trailing whitespace from a string?

What is the difference between print and echo?



Custom Search