characters. You can fix that padding with the trim() function, which takes a
string to trim and returns it with all the whitespace removed from either side.
This is a commonly used function because many strings have an extra new
line at the end or a space at the beginning, and trim() cleans them up
perfectly.
Using trim(), you can turn the 48-character string into a 44-character string
(the same thing but without the extra spaces) like this:
Click here to view code image
echo trim($ourstring);
Keep in mind that trim() returns the trimmed string, so it outputs “The
Quick Brown Box Jumped Over The Lazy Dog”. You can
modify it so trim() passes its return value to strlen() so that the code
trims it and then outputs its trimmed length:
Click here to view code image
echo strlen(trim($ourstring));
PHP always executes the innermost functions first, so the previous code
passes $ourstring through trim(), uses the return value of trim() as
the parameter for strlen(), and prints it.
Of course, everyone knows that boxes do not jump over dogs; the usual
phrase is “the quick brown fox.” Fortunately, there is a function to fix that
problem: str_replace(). Note that it has an underscore in it. (PHP is
inconsistent on this matter, so you really need to memorize the function
names.)
The str_replace() function takes three parameters: the text to search for,
the text to replace it with, and the string you want to work with. When
working with search functions, people often talk about needles and haystacks.
In this situation, the first parameter is the needle (the thing to find), and the
third parameter is the haystack (what you are searching through).
So, you can fix the error and correct box to fox with this code:
Click here to view code image
echo str_replace("Box", "Fox", $ourstring);
There are two little addendums to make here. First, note that we have
specified “Box” as opposed to “box” because that is how it appears in the
text. The str_replace() function is a case-sensitive function, which
means it does not consider “Box” to be the same as “box”. If you want to
do a non-case-sensitive search and replace, you can use the