4.4. Cleaning Strings

Often, the strings we get from files or users need to be cleaned up
before we can use them. Two common problems with raw data are the
presence of extraneous whitespace, and incorrect capitalization
(uppercase versus lowercase).

4.4.1. Removing Whitespace

You can remove leading or trailing
whitespace with the trim( ), ltrim( ), and rtrim( ) functions:

trim( ) returns a copy of
string with whitespace removed from the
beginning and the end. ltrim( ) (the
l is for left) does the
same, but removes whitespace only from the start of the string.
rtrim( ) (the r is for
right) removes whitespace only from the end of
the string.
The optional
charlist argument is a string that
specifies all the characters to strip. The default characters to
strip are given in Table 4-3.

4.4.2. Changing Case

PHP has several
functions for changing the case of
strings: strtolower(
) and
strtoupper( ) operate on entire strings,
ucfirst( ) operates only on the first character of
the string, and ucwords( ) operates on the first
character of each word in the string. Each function takes a string to
operate on as an argument and returns a copy of that string,
appropriately changed. For example:

If you've got a mixed-case string that you want to
convert to "title case," where the
first letter of each word is in uppercase and the rest of the letters
are in lowercase, use a combination of strtolower( ) and ucwords( ):