Specifications
Depending on your particular purpose, you might like to use the ltrim() or chop() functions
instead. They are both similar to trim(), taking the string in question as a parameter and
returning the formatted string. The difference between these three is that trim() removes
whitespace from the start and end of a string, ltrim() removes whitespace from the start (or
left) only, and chop() removes whitespace from the end (or right) only.
Formatting Strings for Presentation
PHP has a set of functions that you can use to reformat a string in different ways.
Using HTML Formatting: the nl2br() Function
The nl2br() function takes a string as parameter and replaces all the newlines in it with the
HTML
<BR> tag. This is useful for echoing a long string to the browser. For example, we use
this function to format the customer’s feedback in order to echo it back:
<p>Your feedback (shown below) has been sent.</p>
<p><? echo nl2br($mailcontent); ?> </p>
Remember that HTML disregards plain whitespace, so if you don’t filter this output through
nl2br(), it will appear on a single line (except for newlines forced by the browser window).
This is illustrated in Figure 4.2.
String Manipulation and Regular Expressions
C
HAPTER 4
4
S
TRING
M
ANIPULATION
97
FIGURE 4.2
Using PHP’s nl2br() function improves the display of long strings within HTML.
Formatting a String for Printing
So far, we have used the echo language construct to print strings to the browser.
PHP also supports a
print() function, which does the same thing as echo, but because it is a
function, it returns a value (0 or 1, denoting success).
06 7842 CH04 3/6/01 3:41 PM Page 97