[Previous] [Contents] [Next]

Trimming whitespace

PHP provides three functions that trim leading or trailing whitespace characters-null, tab, vertical-tab, newline, carriage-return, and space characters-from strings:

string ltrim(string subject)
string rtrim(string subject)
string trim(string subject)

The three functions return a copy of the subject string: trim( ) removes both leading and trailing whitespace characters, ltrim( ) removes leading whitespace characters, and rtrim( ) removes trailing whitespace characters. The following example shows the effect of each:

$var = trim(" Tiger Land\n");  // "Tiger Land"
$var = ltrim(" Tiger Land\n"); // "Tiger Land\n"
$var = rtrim(" Tiger Land\n"); // " Tiger Land"

Rendering newline characters with <br>

Whitespace characters generally don't have any significance in HTML, but it's often useful to preserve newlines when a page is rendered. The nl2br( ) function generates a string by inserting the HTML break element <br /> before all occurrences of the newline character in the source argument:

XHTML-compliant br tag
From PHP Version 4.0.5 onwards, nl2br( ) inserts the XHTML-compliant <br /> markup that includes the shorthand way of closing an empty element. Earlier versions inserted <br>, which isn't valid XML.
string nl2br(string source)

The following example shows how nl2br( ) works:

// A short poem
$verse = "Isn't it funny\n";
$verse .= "That a bear likes honey.\n";
$verse .= "I wonder why he does?\n";
$verse .= "Buzz, buzz, buzz.\n";
// The four lines are rendered as one
echo $verse;
// Renders the poem on four lines in HTML as intended
echo nl2br($verse);

[Previous] [Contents] [Next]