Trim White Space in PHP



Another thing you’ll want to do is to trim the white (blank) space from text
entered into textboxes. This is quite easy, as there’s some useful PHP functions
to help you do this.

Suppose your user has entered this in the textbox:


From the quotation marks, we can see that there is extra space before and after
the text. We can count how many characters this string has with another useful
function: strlen( ). As its name suggests, this returns the length of a string,
By length, we mean how many characters a string has. Try this script:


$space = ” username “;

$letCount = strlen($space);
print $letCount;


When you run the script, you’ll find that the variable contains 14 characters.
However, username has only 8 characters. If you’re checking for an exact match,
this matters!

To remove the white space, you can use the trim( ) function. Change
your script to this:


$space = trim(” username “);

$letCount = strlen($space);
print $letCount;


When you run the script now, you should find that the variable has the correct
number of characters – 8. That’s because the trim( ) function removes
any blank spaces from the left and right of a string.

Two related function are ltrim( ) and rtrim( ). The first one,
ltrim( ), removes space from the beginning of a string; the second one,
rtrim( ), removes space from the end of a string. You can also use these
two functions to trim unwanted characters, as we do much later in the book for
the forum walkthrough.

In the next part, we’ll take a quick look at the shuffle function.


Kaynak : ‘sitesinden alıntı

Yorum Yap